React Hooks are a game-changer for modern web development, empowering developers to build cleaner and more functional code. Whether you're a React newbie or looking to sharpen your skills, here's a breakdown of the most essential React Hooks—complete with examples!
🔑 1. useState
Manage dynamic state in functional components.
const [count, setCount] = useState(0);
function increment() {
setCount(count + 1);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
Use Case: Toggle states, counters, or inputs.
🔑 2. useEffect
Handle side effects like fetching data or interacting with the DOM.
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]); // Only runs when count changes
Use Case: Data fetching, subscriptions, or cleanup.
🔑 3. useContext
Skip prop drilling and share data across components.
const ThemeContext = React.createContext('light');
function App() {
const theme = useContext(ThemeContext);
return <div style={{ background: theme === 'dark' ? '#333' : '#fff' }}>Hello!</div>;
}
Use Case: Global data like themes or authentication.
🔑 4. useReducer
Manage complex state transitions.
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
};
const [state, dispatch] = useReducer(reducer, { count: 0 });
Use Case: State-heavy components like forms or complex UIs.
🔑 5. useRef
Access a mutable reference for DOM elements or persisted variables.
const inputRef = useRef();
return (
<div>
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>
</div>
);
Use Case: DOM access, timers, or animations.
🔑 6. useMemo
Optimize expensive calculations by memoizing their results.
const doubledValue = useMemo(() => number * 2, [number]);
Use Case: Avoid performance bottlenecks during re-renders.
🔑 7. useCallback
Memoize functions to prevent unnecessary re-creations.
const handleClick = useCallback(() => {
console.log('Clicked!');
}, []);
Use Case: Stable functions in child components or event handlers.
🔑 8. Custom Hooks
Reuse your logic across multiple components.
function useFetch(url) {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url).then(response => response.json()).then(setData);
}, [url]);
return data;
}
const data = useFetch('https://api.example.com');
Use Case: DRY code for fetching, authentication, or animations.
🌟 Why Hooks Are a Game-Changer
Hooks simplify React code, reduce boilerplate, and let you focus on building functional, reusable, and maintainable components. Whether you're managing state or optimizing performance, these hooks are your toolbox!
What’s your favorite React Hook?
Let me know in the comments! And if you found this guide useful, follow me here or connect with me on my page: (https://dev.to/tirthorajmondal) 🚀
Top comments (0)