ReactHooksJavaScriptWeb Development
Understanding React Hooks

Muskan
March 21, 2025
Understanding React Hooks
React Hooks are a powerful feature introduced in React 16.8 that allow you to use state and other React features without writing a class.
Why Hooks?
Hooks solve several problems in React:
- Reusing Stateful Logic: Hooks allow you to reuse stateful logic without changing your component hierarchy.
- Complex Components: Hooks let you split one component into smaller functions based on related pieces.
- Classes Confusion: Hooks let you use more of React's features without classes.
Basic Hooks
useState
The useState
hook lets you add state to functional components:
import React, { 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>
);
}
useEffect
The useEffect
hook lets you perform side effects in functional components:
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Custom Hooks
You can create your own Hooks to reuse stateful logic between different components:
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return width;
}
Conclusion
React Hooks provide a more direct API to React concepts you already know: props, state, context, refs, and lifecycle. They enable you to build components with less code and better organization.