This React hooks tutorial walks you through the hooks you will use every day, with short examples you can copy and run. At the end, you will build a small todo app with a custom hook. You only need basic JavaScript (variables, functions, arrays) to follow along.
Hooks let you use state and other React features inside function components. They have been part of React since version 16.8, and today almost all new React code is written with function components and hooks.
What Are React Hooks?
A hook is a special function whose name starts with use. It lets a function component “hook into” React features such as state, side effects and context. Before hooks, you needed a class component to keep state or run code when a component loaded. Now a plain function can do both.
Hooks matter for three reasons:
- Less code. No
this, no constructors, no lifecycle method names to memorize. - Reusable logic. You can share stateful logic between components by writing your own hooks.
- Easier to read. Related code stays together instead of being split across lifecycle methods.
Rules of Hooks
React enforces two simple rules. Break them and you will get bugs or warnings.
- Call hooks only at the top level. Do not call them inside loops, conditions or nested functions.
- Call hooks only from React function components or from other hooks. Do not call them from regular JavaScript functions.
The official ESLint plugin (eslint-plugin-react-hooks) checks both rules for you. Most starter projects include it.
Set Up a React Project
You do not need any special setup to try the examples. The quickest way to start is with Vite. You need Node.js installed.
npm create vite@latest my-hooks-app -- --template react
cd my-hooks-app
npm install
npm run dev
Open the local address that appears in your terminal (usually http://localhost:5173). Edit src/App.jsx to try each example below.
Note: Older tutorials use create-react-app. It is no longer recommended for new projects, so we use Vite here.
useState: Add State to a Component
useState gives a component memory that survives re-renders. It returns a pair: the current value and a function to update it.
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>
);
}
export default Counter;
countis the current state value. It starts at0.setCountupdates the value and tells React to re-render the component.- The value you pass to
useState(0)is only used on the first render.
Use the Updater Form When the New Value Depends on the Old One
If you update state several times in a row, pass a function so you always get the latest value:
setCount((prev) => prev + 1);
Multiple State Variables
You can call useState as many times as you need. Each call is independent:
function SignupForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
return (
<form>
<input value={name} onChange={(e) => setName(e.target.value)} placeholder="Name" />
<input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" />
</form>
);
}
Important: never change state directly (for example todos.push(item)). Always create a new array or object and pass it to the setter.
useEffect: Run Code After Render
useEffect is for side effects: fetching data, updating the page title, setting up a timer or subscribing to an event. React runs your effect after it has updated the screen.
import { useState, useEffect } from 'react';
function Greeting() {
const [name, setName] = useState('World');
useEffect(() => {
document.title = `Hello, ${name}!`;
}, [name]);
return (
<div>
<h1>Hello, {name}!</h1>
<input value={name} onChange={(e) => setName(e.target.value)} />
</div>
);
}
The Dependency Array
| Dependency array | When the effect runs |
|---|---|
[name] |
After the first render, and again whenever name changes |
[] |
Only once, after the first render |
| No array | After every render (rarely what you want) |
Cleaning Up an Effect
If your effect starts something (a timer, an event listener, a subscription), return a function that stops it. React calls it before the next run and when the component is removed.
useEffect(() => {
const id = setInterval(() => console.log('tick'), 1000);
return () => clearInterval(id);
}, []);
In development, React Strict Mode runs effects twice on purpose to help you catch missing cleanups. This only happens in development, not in production.
Example: Fetching Data
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let ignore = false;
async function loadUser() {
try {
setLoading(true);
const res = await fetch(`/api/users/${userId}`);
if (!res.ok) throw new Error('Request failed');
const data = await res.json();
if (!ignore) setUser(data);
} catch (err) {
if (!ignore) setError(err.message);
} finally {
if (!ignore) setLoading(false);
}
}
loadUser();
return () => { ignore = true; };
}, [userId]);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return <div>{user.name}</div>;
}
The ignore flag stops an old request from overwriting newer data if userId changes while the request is still running. For larger apps, many teams use a data library such as TanStack Query instead of writing this by hand.
useRef: Keep a Value Without Re-Rendering
useRef holds a value that stays the same between renders. Changing it does not trigger a re-render. The most common use is reaching a DOM element:
import { useRef } from 'react';
function FocusInput() {
const inputRef = useRef(null);
return (
<div>
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus the input</button>
</div>
);
}
useContext: Share Data Without Prop Drilling
Context lets a parent share a value with any component below it, without passing props through every level. A common example is a theme:
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext value={theme}>
<Toolbar />
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle theme
</button>
</ThemeContext>
);
}
function Toolbar() {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
}
In React 19 you can render the context object directly as a provider (<ThemeContext value=...>). In older versions, use <ThemeContext.Provider value=...> instead.
useReducer: Manage More Complex State
When state has several related values or many ways to change, useReducer keeps the update logic in one place:
import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
case 'decrement': return { count: state.count - 1 };
case 'reset': return { count: 0 };
default: throw new Error('Unknown action');
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</div>
);
}
useMemo and useCallback: Performance Hooks
These two hooks remember a calculation (useMemo) or a function (useCallback) between renders, so React can skip repeated work. Beginners often use them too early. Start without them, and add them only when you measure a real performance problem.
Build a Custom Hook
A custom hook is a function whose name starts with use and that calls other hooks. It lets you reuse logic across components. This one saves state to the browser’s localStorage:
// src/useLocalStorage.js
import { useState, useEffect } from 'react';
export 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];
}
You use it exactly like useState, but the value survives a page refresh.
Project: Build a Todo App With Hooks
Now let’s combine useState and our custom hook into a small todo app. Replace the contents of src/App.jsx with this:
import { useState } from 'react';
import { useLocalStorage } from './useLocalStorage';
import './App.css';
function App() {
const [todos, setTodos] = useLocalStorage('todos', []);
const [input, setInput] = useState('');
const addTodo = () => {
const text = input.trim();
if (!text) return;
setTodos([...todos, { id: Date.now(), text, completed: false }]);
setInput('');
};
const toggleTodo = (id) => {
setTodos(todos.map((t) => (t.id === id ? { ...t, completed: !t.completed } : t)));
};
const deleteTodo = (id) => {
setTodos(todos.filter((t) => t.id !== id));
};
return (
<div className="app">
<h1>My Todo List</h1>
<div className="input-container">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && addTodo()}
placeholder="Add a new todo..."
/>
<button onClick={addTodo}>Add</button>
</div>
<ul className="todo-list">
{todos.map((todo) => (
<li key={todo.id} className={todo.completed ? 'completed' : ''}>
<input
type="checkbox"
checked={todo.completed}
onChange={() => toggleTodo(todo.id)}
/>
<span>{todo.text}</span>
<button onClick={() => deleteTodo(todo.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
}
export default App;
Add some basic styling in src/App.css:
.app { max-width: 600px; margin: 50px auto; font-family: Arial, sans-serif; }
.input-container { display: flex; gap: 10px; margin-bottom: 24px; }
.input-container input { flex: 1; padding: 10px; font-size: 16px; }
.todo-list { list-style: none; padding: 0; }
.todo-list li { display: flex; align-items: center; gap: 12px; padding: 12px; border: 1px solid #eee; margin-bottom: 8px; }
.todo-list li span { flex: 1; }
.todo-list li.completed span { text-decoration: line-through; color: #888; }
Run the app, add a few todos and refresh the page. Your list is still there, because the custom hook saved it to localStorage.
Common Mistakes to Avoid
- Changing state directly. Use the setter and create a new array or object.
- Missing dependencies. If your effect uses a value from the component, put it in the dependency array.
- Infinite loops. Updating state inside an effect that depends on that same state, without a condition, re-runs the effect forever.
- Forgetting cleanup. Always stop timers and remove listeners you create in an effect.
- Calling hooks conditionally. Keep hooks at the top level of the component.
- Overusing
useEffect. If you can calculate a value during render, do that instead of storing it in state with an effect.
Frequently Asked Questions
What is the best way to learn React hooks?
Start with useState and useEffect, build one small project (like the todo app above), then add useRef, useContext and useReducer as you need them. The official React documentation at react.dev is free and includes interactive examples.
Do I still need class components?
For new code, no. Function components with hooks are the standard. Class components still work, and you may see them in older projects.
Can I use hooks inside a class component?
No. Hooks only work in function components and custom hooks.
What is the difference between useState and useRef?
Changing state re-renders the component. Changing a ref does not. Use state for values shown on screen, and refs for values you only need to remember (like a DOM element or a timer ID).
Should I learn hooks before Next.js?
Yes. Frameworks like Next.js are built on React, so knowing components, props, state and hooks first makes them much easier to learn.
Summary
- useState adds state to a component.
- useEffect runs side effects such as data fetching, with a dependency array and optional cleanup.
- useRef stores a value or DOM element without causing a re-render.
- useContext shares data across the component tree.
- useReducer handles more complex state logic.
- Custom hooks let you reuse logic between components.
Next, try extending the todo app with filters (all, active, completed), or fetch some todos from a public API with useEffect.