title: "Understanding React Hooks: A Comprehensive Guide"
date: 2026-04-15
readingTime: 2 min read
tags: ["Front End", "React", "JavaScript"]
React Hooks revolutionized how we write React components. Let's explore the most commonly used hooks and learn how to use them effectively.
The useState hook allows you to add state to functional components.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
const [state, setState] = useState(() => {
const initialState = someExpensiveComputation(props);
return initialState;
});
setCount(prevCount => prevCount + 1);
The useEffect hook handles side effects in functional components.
import { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetchUser(userId).then(setUser);
}, [userId]);
return user ? <div>{user.name}</div> : <div>Loading...</div>;
}
useEffect(() => {
let isMounted = true;
fetchData().then(data => {
if (isMounted) {
setData(data);
}
});
return () => {
isMounted = false;
};
}, []);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
Create reusable logic by extracting it into custom hooks:
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = (value) => {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
};
return [storedValue, setValue];
}
React Hooks provide a powerful and elegant way to manage state and side effects. Master them, and you'll write cleaner, more maintainable React code.
Stay tuned for more React tips and tutorials!