• Home
  • React
  • React Hooks – useMemo hook example

React Hooks – useMemo hook example

UseMemo hook returns memoized value. That’s why you can use it to optimize performance of your app. If you have large calculations to get value that you need, you can do it only once and use useMemo hook to remember this value.

When you pass a function to useMemo hook , it will call it in first render, and in every other renders it will return memorized value, so we can avoid costly calculations in every re-render (unless dependencies have change, then function will be called again, to get and remember new value).

Let’s imagine, we have counter and two buttons, that changing its value. When we click on any of button, counter value will change and component will re-render.

Now imagine, that on the same site we have “memo” value, which is sum of two digits. Functionality of adding digits is wrapped by useMemo function, so addition is made only once, and every time, that we click on buttons, that change counter, sum of addition is returned from memory.

Below code clearly represent this example:

const HookExample = () => {    
    const [counter, setCounter] = useState(0);
    const [numbers, setNumbers] = useState({a: 5, b: 7})

    // if your calculations will be wrapped in useMemo, it will be re-render only if dependencies will change
    // otherwise it will be "read value from memory"
    const memo = useMemo(() => { 
        // here you can add some calculations
        console.log("calculations are made here");
        return numbers.a + numbers.b
    }, [numbers]);

    return (
        <div className="App">
            <p>Counter: {counter}</p>
                <button onClick={() => setCounter(counter-1) }>-1</button>
                <button onClick={() => setCounter(counter+1) }>+1</button>
            <p>Memo: {numbers.a} + {numbers.b} = {memo}</p>
                <button onClick={() => setNumbers({a: numbers.a + 1, b: numbers.b + 2}) }>Change memo numbers</button>

export default HookExample;

click on DEMO to see how useMemo hook works

You can find this code in repo: https://github.com/love-coding-pl/React-Hooks-Examples/tree/Hook-6-useMemo


Leave a Reply

Your email address will not be published. Required fields are marked *