DEV Community

Discussion on: Optimize React Hooks Performance

Collapse
 
pyeongoh profile image
pyeong_oh

your last exmaple or example with useCallback for prevent re-rendering is not working, when every input changed, counter component is re-rendered.

If you want prevent re-rendering counter compnent when input value changed, changed the useCallback's sencond array paramter [value] to []

Input changes means value is changed, so useCallback always return new addHello, counter component receive new referenced function so it always re-rendered, that is why your last example is not working.

Collapse
 
rahmanfadhil profile image
Abdurrahman Fadhil

Hmm, I don't think so...

We don't use useCallback to prevent re-rendering counter component. We use it to memoize our function (the one that add "Hello!" to the "value" state). When you memoize your function with useCallback, the component is still being re-rendered but the returned value of the memoized function is cached. This is very helpful if you want to do expensive task that requires a lot of time.

We put [value] because we always want to update our function when the "value" state changes, because we need "value" state inside our function. So, our function is still being memoized unless the "value" state has changed.

But thanks for the feedback anyway 😃