React – useMemo hook – Example

React

React lets you build user interfaces out of individual pieces called components. Create your own React components like Thumbnail, LikeButton, and Video. Then combine them into entire screens, pages, and apps.

useMemo is a React hook that lets you cache the result of a calculation between re-renders. Call useMemo at the top level of your component to cache a calculation between re-renders.

During next renders, useMemo will either return an already stored value from the last render (if the dependencies haven’t changed), or call callback again, and return the result that callback has returned.  

The useMemo hook uses the second parameter to declare its dependency. The function will only run when its dependency has changed.

Example


import React, {useState, useMemo} from 'react';

export function App(props) {

  const [count, setCount] = useState(0);
  const memoResult = useMemo(() => operation(count), [count]);

  const increment = (incrementValue) => {
    setCount((c) => c + incrementValue);
  };

  function operation(num) {
    console.log("Calculating new value");
    return num + 1;
  };

  return (
    <div>
      <div>
        <div>Count: {count}</div>
        <hr/>
        <div><button onClick={()=>{ increment(0)}}>+0</button> previous value (no dependency change)</div>        
        <div><button onClick={()=>{ increment(1)}}>+1</button> new value (dependency changed)</div>
        <hr/>
        <h2>useMemo value</h2>
        {memoResult}
      </div>
    </div>
  );
};
https://www.mldgroup.com

Vyštudovaný top manažér pôsobiaci najmä ako manažér, marketér, softvérový inžinier, konzultant, bloger, YouTuber a zatiaľ neúspešný hudobník a producent. V rámci praxe pôsobil v rôznych odvetviach na rôznych pozíciách v malých aj veľkých firmách, vrátane spoluprác a partnerstiev s významnými firmami či poradenskými spoločnosťami.

Pridaj komentár

Vaša e-mailová adresa nebude zverejnená. Vyžadované polia sú označené *