React Hooks revolutionized how we write React components. This tutorial covers everything you need to know.
Introduction to Hooks
Hooks let you use state and other React features without writing a class component.
useState Hook
The most basic hook for managing state:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
useEffect Hook
Handle side effects in your components:
import { useEffect, useState } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/api/data')
.then(res => res.json())
.then(setData);
}, []);
return <div>{data?.title}</div>;
}
Custom Hooks
Create reusable logic:
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const saved = localStorage.getItem(key);
return saved ? JSON.parse(saved) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
Best Practices
- Always call hooks at the top level
- Only call hooks from React functions
- Use ESLint plugin for hooks
- Keep custom hooks focused and reusable
Conclusion
Hooks make React code more readable and maintainable. Practice these patterns and explore more advanced hooks like useReducer and useContext.