
React Hooks Explained: useState, useEffect, useRef, useMemo, and Custom Hooks
Table of contents
- useState
- When to use it
- Common patterns
- What it's not for
- useEffect
- Cleanup
- When to use it
- What to watch out for
- useRef
- The two main uses
- When to use it
- React 19 update: no more forwardRef
- What it's not for
- useMemo
- When to use it
- When NOT to use it
- useMemo vs useCallback
- When to Write a Custom Hook
- Example: useLocalStorage
- Example: useFetch
- When to extract a custom hook
- Quick Reference
- Final Thoughts
- Resources
Hooks changed how React works.
Before them, you had class components, lifecycle methods, and a lot of boilerplate. After hooks, you could manage state, side effects, and shared logic all from a plain function.
But knowing that hooks exist and knowing when to reach for each one are two different things.
This post walks through the hooks you'll use the most, useState, useEffect, useRef, useMemo, and finishes with how to recognize when it's time to write your own custom hook.
useState
useState is the most fundamental hook. It lets a component remember something between renders.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}useState returns two things: the current value and a function to update it. When you call the setter, React re-renders the component with the new value.
When to use it
- Any value the component needs to track and display
- Form inputs
- Toggle states (open/closed, visible/hidden)
- Data fetched from an API
Common patterns
Updating based on previous value
When your next state depends on the current state, use the function form of the setter. This avoids stale closure bugs:
setCount(prev => prev + 1);Object state
When your state is an object, you need to spread the existing state, React doesn't merge object updates automatically:
const [user, setUser] = useState({ name: '', email: '' });
setUser(prev => ({ ...prev, name: 'JC' }));Lazy initialization
If the initial value is expensive to compute, pass a function instead of a value. It only runs once:
const [data, setData] = useState(() => JSON.parse(localStorage.getItem('data') || '[]'));What it's not for
Don't use useState for values that don't affect what's rendered. If you're storing something just to reference it later without triggering a re-render, that's a job for useRef.
useEffect
useEffect lets you run code in response to something happening, a component mounting, a value changing, or a component unmounting.
import { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
const fetchUser = async () => {
const res = await fetch(`/api/users/${userId}`);
const data = await res.json();
setUser(data);
};
fetchUser();
}, [userId]);
if (!user) return <p>Loading...</p>;
return <h2>{user.name}</h2>;
}The second argument, the dependency array, controls when the effect runs:
| Dependency array | When the effect runs |
|---|---|
| Not provided | After every render |
[] (empty) | Once, when the component mounts |
[value] | On mount, and whenever value changes |
Cleanup
If your effect sets up something that needs to be torn down, an event listener, a timer, a subscription, return a cleanup function:
useEffect(() => {
const handleResize = () => console.log(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);The cleanup runs before the next effect fires and when the component unmounts.
When to use it
- Fetching data when a component mounts or a prop changes
- Setting up and tearing down event listeners
- Syncing with external systems (browser APIs, third-party libraries)
- Running code after a specific value changes
What to watch out for
Missing dependencies in the array is the most common useEffect mistake. If your effect uses a value from the component, it should be in the array, otherwise you'll read stale data.
Also, don't use useEffect for derived values. If you can compute something directly from existing state or props, just compute it inline:
// Don't do this
const [fullName, setFullName] = useState('');
useEffect(() => {
setFullName(`${firstName} ${lastName}`);
}, [firstName, lastName]);
// Do this instead
const fullName = `${firstName} ${lastName}`;useRef
useRef gives you a mutable container that persists across renders, but updating it does not trigger a re-render.
That's the key difference from useState. When you change ref.current, nothing re-renders.
The two main uses
1. Accessing a DOM element directly
import { useRef } from 'react';
function SearchInput() {
const inputRef = useRef(null);
function handleFocus() {
inputRef.current.focus();
}
return (
<div>
<input ref={inputRef} type="text" placeholder="Search..." />
<button onClick={handleFocus}>Focus</button>
</div>
);
}Attach ref to a JSX element and ref.current becomes the actual DOM node.
2. Storing a value without triggering re-renders
import { useRef, useEffect } from 'react';
function Timer() {
const intervalRef = useRef(null);
function start() {
intervalRef.current = setInterval(() => {
console.log('tick');
}, 1000);
}
function stop() {
clearInterval(intervalRef.current);
}
return (
<div>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
</div>
);
}The interval ID is stored in the ref. Updating it doesn't re-render the component, it just holds the value so you can reference it later.
When to use it
- Managing focus, scroll position, or other DOM interactions
- Storing timers or intervals
- Keeping a previous value around without affecting renders
- Referencing a value inside an effect or callback without adding it to the dependency array
React 19 update: no more forwardRef
In React 19, you no longer need forwardRef to pass a ref down to a child component. Refs are now just props:
// Before React 19 โ required forwardRef
const Input = forwardRef((props, ref) => <input ref={ref} {...props} />);
// React 19 โ just pass ref like any other prop
function Input({ ref, ...props }) {
return <input ref={ref} {...props} />;
}
// Usage is the same either way
const inputRef = useRef(null);
<Input ref={inputRef} />useRef itself isn't going anywhere, this change just removes the boilerplate wrapper you used to need when sharing refs across components.
What it's not for
Don't use useRef to store values that your UI needs to display. If the UI depends on a value, it belongs in useState.
useMemo
useMemo caches the result of a calculation and only recomputes it when its dependencies change.
import { useState, useMemo } from 'react';
function ProductList({ products, filterTerm }) {
const filtered = useMemo(() => {
return products.filter(p =>
p.name.toLowerCase().includes(filterTerm.toLowerCase())
);
}, [products, filterTerm]);
return (
<ul>
{filtered.map(p => <li key={p.id}>{p.name}</li>)}
</ul>
);
}Without useMemo, filtered would be recomputed on every render, even if products and filterTerm haven't changed. With it, the computation only runs when those values actually change.
When to use it
- Expensive computations (sorting, filtering, transforming large arrays)
- Derived values that are calculated from props or state
- Values passed as props to memoized child components where you want to avoid unnecessary re-renders
When NOT to use it
This is the one hook people overuse.
useMemo has overhead, it stores a cached value and compares dependencies on every render. For simple computations, that overhead costs more than just recomputing the value.
// Don't do this, useMemo costs more than the calculation
const doubled = useMemo(() => count * 2, [count]);
// Just do this
const doubled = count * 2;A good rule: if you can't measure a performance problem, don't add useMemo to fix one. Reach for it when you have a genuinely expensive operation and can verify it's causing slowness.
useMemo vs useCallback
useCallback is the same idea but for functions instead of values:
// useMemo โ caches a value
const sortedList = useMemo(() => [...items].sort(), [items]);
// useCallback โ caches a function
const handleClick = useCallback(() => {
doSomething(id);
}, [id]);Use useCallback when you're passing a function as a prop to a memoized child component and want to avoid unnecessary re-renders.
When to Write a Custom Hook
A custom hook is just a function that starts with use and calls other hooks.
That's it. No magic. No special API.
The reason to write one is reuse and separation of concerns. If you find yourself copying the same stateful logic across multiple components, that logic belongs in a custom hook.
Example: useLocalStorage
Instead of writing localStorage sync logic in every component that needs it:
import { useState } from 'react';
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch {
return initialValue;
}
});
function setValue(value) {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.error(error);
}
}
return [storedValue, setValue];
}Now any component can use it like useState but with persistence:
function Settings() {
const [theme, setTheme] = useLocalStorage('theme', 'light');
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Current theme: {theme}
</button>
);
}Example: useFetch
Data fetching logic that you'd otherwise repeat in every component:
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let cancelled = false;
const fetchData = async () => {
setLoading(true);
try {
const res = await fetch(url);
const json = await res.json();
if (!cancelled) {
setData(json);
setLoading(false);
}
} catch (err) {
if (!cancelled) {
setError(err);
setLoading(false);
}
}
};
fetchData();
return () => { cancelled = true; };
}, [url]);
return { data, loading, error };
}Usage:
function BlogPost({ slug }) {
const { data: post, loading, error } = useFetch(`/api/blogs/${slug}`);
if (loading) return <p>Loading...</p>;
if (error) return <p>Something went wrong.</p>;
return <article>{post.content}</article>;
}The cancelled flag in the cleanup prevents a state update on an unmounted component, a common async bug that custom hooks can encapsulate and hide from callers.
When to extract a custom hook
Ask yourself these questions:
- Am I writing the same
useState+useEffectcombination in more than one component? - Is the logic complex enough that it obscures what the component is actually doing?
- Do I want to test this logic independently from the UI?
If yes to any of these, it's time to extract a hook.
The goal isn't abstraction for its own sake. It's keeping components readable and logic reusable.
Quick Reference
| Hook | What it does | Re-renders on change? |
|---|---|---|
useState | Stores values the UI depends on | Yes |
useEffect | Runs side effects after render | No (triggers renders indirectly) |
useRef | Stores values or DOM refs | No |
useMemo | Caches expensive computations | No |
useCallback | Caches functions | No |
| Custom hook | Encapsulates reusable stateful logic | Depends on what's inside |
Final Thoughts
The hooks you'll use in almost every component are useState and useEffect. Get those solid first.
useRef is your escape hatch when you need to touch the DOM or hold a value without triggering renders.
useMemo is a performance tool, not a default. Only reach for it when you can measure a real problem.
And custom hooks are the move when you notice yourself copy-pasting stateful logic. The moment a piece of logic has its own lifecycle, its own state, and its own concerns, it's a hook waiting to be written.
Resources
- React Docs: Hooks Reference
- React Docs: Custom Hooks
- useHooks.com, collection of production-ready custom hooks
If you want to talk through a specific hooks pattern or problem you're working through, hit me up on LinkedIn.

Discussion
Comments
Loading comments...