Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to memoize custom React hook

const useSomeHook = ({number}) => {
  const [newNumber, setNewNumber] = useState(0)

  useEffect(() => {
    setNewNumber(number + 1)
  }, [number])
}

const SomeComponent = ({number, value, ...restProps}) => {

  useSomeHook({number})


  return <div>{number}</div>
}

Let's imagine I have this case. Each time when in SomeComponent come some new prop, it will call my useSomeHook hook, but I want to prevent it. I want to call it only when the number is changed (memoize it). In other cases, don't touch it. But I haven't found any solving with this case. Could you help me solve this issue?

like image 905
Andrey Radkevich Avatar asked Apr 26 '20 09:04

Andrey Radkevich


People also ask

Can you memoize a React component?

Since components are just functions though, they can be memoized using React. memo() . This prevents the component from re-rendering unless the dependencies (props) have changed. If you have a particularly heavy component then it is best to memoize it, but don't memoize every component.

Which hook do we use to memoize return values?

React has a built-in hook called useMemo that allows you to memoize expensive functions so that you can avoid calling them on every render. You simple pass in a function and an array of inputs and useMemo will only recompute the memoized value when one of the inputs has changed.


1 Answers

You can not prevent calling hook, this will lead to invariant violation error. Every hook in component should be executed on each render. You should rely on useEffect dependencies argument to run conditional code only if value changes.

like image 88
Aleksey Avatar answered Oct 24 '22 07:10

Aleksey