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.
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"45const App = () => {6 const [inputValue, setInputValue] = useState("")78 return (9 <div>10 <Header />1112 <section>13 <h2>Hello 👋</h2>14 <input15 placeholder="Enter your name"16 value={inputValue}17 type="text"18 onChange={(e) => setInputValue(e.target.value)}19 />20 </section>2122 <Footer />23 </div>24 )25}
And in the Footer:
1const Footer = () => {2 const quotes = [3 /* a list of motivational quotes */4 ]56 const index = Math.floor(Math.random() * quotes.length)7 const randomQuote = quotes[index]89 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.
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"23const Footer = () => {4 const quotes = [5 /* your quote list */6 ]78 const randomQuote = useMemo(() => {9 const index = Math.floor(Math.random() * quotes.length)10 return quotes[index]11 }, []) // only runs once1213 return <footer>"{randomQuote}"</footer>14}
By passing an empty dependency array to useMemo(), we ensure that randomQuote is only calculated once on mount.
Check out the full walkthrough in this video:
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:
Use useMemo() when:
You’re doing expensive calculations
You want to cache computed values
A child component's logic shouldn't run on every parent render
Avoid overusing it — it's not needed for simple values or static data.
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.