React Hooks: useEffect vs useCallback vs useMemo
When learning React, I came across three important hooks: useEffect, useCallback, and useMemo. At first, I found them confusing because they all use dependency arrays. But after understanding their purpose, I realized
When learning React, I came across three important hooks: useEffect, useCallback, and useMemo.
At first, I found them confusing because they all use dependency arrays.
But after understanding their purpose, I realized that each hook solves a different problem.
Let's understand them with simple examples.
1. What is useEffect?
useEffect is used to perform an action after a component renders.
For example, when we want to update the browser tab title whenever a counter changes.
import { useState, useEffect } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = count;
}, [count]);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
Here, whenever count changes, useEffect updates the browser tab title.
In simple words:
useEffect is used to perform actions after rendering.
2. What is useCallback?
useCallback is used to remember a function between renders.
Let's say we have a function that prints a message.
import { useCallback } from "react";
function App() {
const sayHello = useCallback(() => {
console.log("Hello");
}, []);
return <button onClick={sayHello}>Click me</button>;
}
Here, React remembers the function instead of creating a new function on every render.
The function will still work when we click the button.
In simple words:
useCallback remembers a function.
3. What is useMemo?
useMemo is used to remember the result of a calculation.
For example, calculating the total price of products.
import { useMemo } from "react";
function App() {
const price = 100;
const quantity = 5;
const total = useMemo(() => {
return price * quantity;
}, [price, quantity]);
return <h2>Total: {total}</h2>;
}
Here, React calculates the total price and remembers the result.
If the dependencies do not change, React can reuse the previous result.
In simple words:
useMemo remembers a calculated value.
4. What is the difference?
Let's imagine we are building a shopping application.
-
useEffect→ Fetches products from an API. -
useCallback→ Remembers a function that adds a product to the cart. -
useMemo→ Remembers the total price of the cart.
The easiest way to remember these hooks is:
-
useEffect→ Do something. -
useCallback→ Remember a function. -
useMemo→ Remember a value.
Conclusion
All three hooks are useful in React, but they have different purposes.
We don't need to use them in every component. We should use them when they solve a real problem.
Each hook has its own purpose. Use only the hooks you need to make your component work better.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.