- Published on
๐ Mastering React Hooks - useState, useEffect, useContext, useReducer & Custom Hooks ๐ฏ
- Authors
- Name
- Mukta Patel
- @muktaTechTonic
React Hooks are game-changers! ๐ฎ They allow you to manage state and side effects in functional components without needing class components. In this guide, we'll dive deep into some of the most essential hooks: useState, useEffect, useContext, useReducer and how to create your own custom hooks! ๐ฅ
๐ข useState โ Managing State Like a Pro ๐
The useState hook helps you add state to functional components. It returns a state variable and a function to update it.
Example:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
</div>);
}
๐ Key takeaway: Always update state using the setter function, never modify the state directly!
๐ต useEffect โ Handling Side Effects ๐ก
The useEffect hook is used for side effects like data fetching, subscriptions, and manually manipulating the DOM.
Example:
import { useState, useEffect } from 'react';
function Timer(){
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => setSeconds(s => s+1), 1000);
return () => clearInterval(intervalId); // Cleanup function
}, []); // Run only once, when component mounts;
return <p>โณ Timer: {seconds} seconds</p>;
}
๐ Pro Tip: Always clean up effects to avoid memory leaks! ๐งน
๐ด useContext โ Sharing State Across Components ๐
The useContext hook is used to share state between components without passing props down (prop drooling) manually.
Example:
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
function ThemedComponent() {
const theme = useContext(ThemeContext);
return <p style={{ color: theme === 'dark' ? 'white' : 'black'}}>Current Theme: {theme}</p>;
}
โจ Best Practice: Combine useContext with useReducer for advanced state management! ๐ช
๐ต useReducer โ Managing Complex State ๐คฏ
The useReducer hook is an alternative to useState for managing complex state logic.
Example:
import { useReducer } from 'react';
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:
return state;
}
}
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>
);
}
๐ก Why use useReducer?
โ
Great for managing complex state logic ๐
โ
Works well with useContext for global state management ๐
โ
Keeps state updates predictable and structured ๐ฏ \
๐ Custom Hooks โ Reusability at Its Best ๐ฅ
Custom hooks allow you to extract reusable logic from components.
Example:
import { useState, useEffect } from 'react';
function useFetch(url){
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then(response => response.json())
.then(data => {
setData(data);
setLoading(false);
})
.catch(error => console.error('Error:', error));
}, [url]); // re-run effect if url changes
return [data, loading];
}
๐ก Why use Custom Hooks?
โ
Clean, reusable code โจ
โ
Extract logic from components ๐๏ธ
โ
Improve readability and maintainability ๐ \
๐ฏ Wrapping Up
React Hooks make functional components more powerful and flexible! ๐ฅ Whether you're managing state with useState, handling side effects with useEffect, using useContext for global state, useReducer for complex state logic, or creating custom hooks for reusability, mastering these hooks will level up your React skills. ๐ Happy Coding! ๐ปโจ