Back to Notes

Stop Unwanted Re-renders in React with useMemo()

When building React apps, it's common to run into unnecessary re-renders — especially when parent state updates trigger child components to re-render even when their logic or UI hasn't changed.

In this post, we'll walk through a real-world example of this issue and how to fix it using the useMemo() hook.


🚨 The Problem

Let’s say we have a simple app with an input field and a Footer component that displays a random quote:

1import React, { useState } from "react"
2import Header from "./components/Header"
3import Footer from "./components/Footer"
4
5const App = () => {
6 const [inputValue, setInputValue] = useState("")
7
8 return (
9 <div>
10 <Header />
11
12 <section>
13 <h2>Hello 👋</h2>
14 <input
15 placeholder="Enter your name"
16 value={inputValue}
17 type="text"
18 onChange={(e) => setInputValue(e.target.value)}
19 />
20 </section>
21
22 <Footer />
23 </div>
24 )
25}

And in the Footer:

1const Footer = () => {
2 const quotes = [
3 /* a list of motivational quotes */
4 ]
5
6 const index = Math.floor(Math.random() * quotes.length)
7 const randomQuote = quotes[index]
8
9 return <footer>"{randomQuote}"</footer>
10}

Now every time you type in the input, the entire App re-renders, including the Footer. As a result, the quote changes — even though the input has nothing to do with the footer.


✅ The Fix: useMemo()

We can fix this behavior using React’s useMemo() hook. It lets us memoize the result of a computation so that it doesn't re-run on every render unless its dependencies change.

Here's how we can use it in the Footer component:

1import React, { useMemo } from "react"
2
3const Footer = () => {
4 const quotes = [
5 /* your quote list */
6 ]
7
8 const randomQuote = useMemo(() => {
9 const index = Math.floor(Math.random() * quotes.length)
10 return quotes[index]
11 }, []) // only runs once
12
13 return <footer>"{randomQuote}"</footer>
14}

By passing an empty dependency array to useMemo(), we ensure that randomQuote is only calculated once on mount.


🎥 Watch It in Action

Check out the full walkthrough in this video:

Stop Unwanted Re-renders in React with useMemo()
@engineeringwithaman
Watch on YouTube

⚡ Why This Matters

React will re-render child components whenever the parent changes — even if the child doesn't use any updated props or state. This can cause performance issues or unintended UI changes.

Using useMemo() helps you:


🧠 When to Use useMemo()

Use useMemo() when:

Avoid overusing it — it's not needed for simple values or static data.


👋 Final Thoughts

useMemo() is a powerful tool when used thoughtfully. It can help improve your app's performance and prevent subtle bugs caused by unnecessary re-renders.

Back to Notes