docs / React
React Hooks Complete Guide
Master React hooks with this comprehensive guide covering useState, useEffect, useContext, and custom hooks.
2 min read
React Hooks Complete Guide
React Hooks revolutionized how we write React components by enabling the use of state and other React features without writing classes. This guide covers all the essential hooks and best practices.
useState Hook
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 Hook
The useEffect hook lets you perform side effects in function components:
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
// Cleanup function (optional)
return () => {
document.title = 'React App';
};
}, [count]); // Only re-run if count changes
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}Custom Hooks
Create your own hooks to reuse stateful logic between components:
import { useState, useEffect } from 'react';
function useWindowSize() {
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined,
});
useEffect(() => {
function handleResize() {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}
window.addEventListener('resize', handleResize);
handleResize(); // Set initial size
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowSize;
}Use your custom hook in any component:
function ResponsiveComponent() {
const size = useWindowSize();
return <div>{size.width > 768 ? <h1>Desktop View</h1> : <h1>Mobile View</h1>}</div>;
}