Advanced React Hooks Tutorial
Welcome to the Advanced React Hooks guide! If you're already familiar with the basics, let's dive deeper into mastering these powerful tools. 🚀
1. Custom Hooks
Custom Hooks allow you to reuse stateful logic across components. For example:
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error(error);
return initialValue;
}
});
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
console.error(error);
}
}, [key, storedValue]);
return [storedValue, setStoredValue];
}
2. useReducer
for Complex State
When managing complex state logic, useReducer
is a better fit than useState
. It's especially useful for:
- State that depends on previous state
- Multiple sub-values
- Complex state transitions
Example:
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}
3. Context API for Global State
Use useContext
to access global state without prop drilling. Here's how to set it up:
- Create a context with
createContext
- Provide the context in a parent component
- Consume it in child components with
useContext
🔗 Learn more about Context API
4. Advanced useEffect
Techniques
useEffect
can be used for:
- Side effects like API calls or subscriptions
- Cleanup functions to prevent memory leaks
- Conditional rendering based on dependencies
Example:
useEffect(() => {
const timer = setTimeout(() => {
console.log('This will run after 3 seconds');
}, 3000);
return () => clearTimeout(timer);
}, []);
5. Hook Best Practices
- Always use Hooks at the top level of your React function
- Avoid using Hooks inside loops or conditionals
- Use
useCallback
to optimize performance - Follow the official React Hooks rules