React.useMemo code example

Example 1: usememo hook react

const [a,setA]=useState(0);
const [b,setB]=useState(0);

const pow=(a)=>{
  return Math.pow(a,2);
}

var val= useMemo(()=>{
  return pow(a);  // calling pow function using useMemo hook
},[a]); // only will be called once a will changed (for "a" we can maintain state)


return(
  
   <input type="text" onChange={(e)=>{setA(e.target.value)}}>
   <input type="text" onChange={(e)=>{setB(e.target.value)}}>
  
  

  {val} // to access the value from useMemo
)

Example 2: react usememo

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

Returns a memoized value.

Pass a “create” function and an array of dependencies. useMemo will only recompute the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render.

Remember that the function passed to useMemo runs during rendering. Don’t do anything there that you wouldn’t normally do while rendering. For example, side effects belong in useEffect, not useMemo.

If no array is provided, a new value will be computed on every render.

You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance.