DEV Community

Optimize React Hooks Performance

Rahman Fadhil on June 04, 2019

Read the original article here According to the official React documentation, Hooks are functions that let you "hook into" React state and lifecyc...
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
Rahman 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 😃

Collapse
 
liuxinqiong profile image
Ethan

Thanks

Collapse
 
alabobriggs profile image
Alabo David Briggs

After memoising the Counter component with useCallback and useMemo is there still a need to use React.memo?

Collapse
 
rahmanfadhil profile image
Rahman Fadhil

Yes, if you want to pass data to the child component via props.