Check the code below:
usecallback-demo-1-component-renders-unnecessarily - Code
You can run the app
directly:
usecallback-demo-1-component-renders-unnecessarily - App
Whenever the button
is clicked, the 'increment rendered' message is logged in console. This means,
we're rendering the Increment component unnecessarily.
The Increment
component is rendered every time à because it depends on increment method à this method again depends on count state à so, whenever the count state
changes, since count state is a dependency of Increment component,
this must be rendered everytime.
However, consider the
following code where this problem is solved (of course using random number
instead of count for demo):
usecallback-demo-2-usecallback-prevents-unnecessary-renders
- Code
Here, we're caching
the increment method using useCallback hook.
The Increment component is not rendered every time. It is
rendered only on the initial load.
According to Hooks
documentation, useCallback returns a memoized callback.
What does that mean?
It means, it returns cached result.
Is that true? In that
case, it should always return the same random number when we click the button
but we get different values.
So, the above
definition should be – it returns cached method (not cached value). This is the
reason why though the increment method is called multiple
times, the Increment component is rendered only once à because, the Increment component
is not dependent on any of the variables inside the increment method
(Random is not a dependency but count state is), and it is
happy to cache the entire method (callback).
usecallback-demo-2-usecallback-prevents-unnecessary-renders
- App
Courtesy: Thanks to this Youtube Video
Comments
Post a Comment