Thursday, January 27, 2022

Set dependent array parameter in useCallback (and other react) hooks

React callback hook creates memorized callback function, the memorized callback function gets created once, but will be invoked later for many times. If the callback function uses any values returned by useState() hook, then those values must be included in the useCallback's dependent array parameter. The reason is when useCallback is created, it captures all the closure variables as a snapshot for future usage. After that, if some values are updated by calling set method of useState() hook, the updated values will be not reflected in the closure snapshot captured by useCallback hook when it was created, so when the callback hook method is called after its creating, it will still use the original out-of-date values it captured when it was created. 

So as a simple rule, when defining hooks with dependent parameters, always including all values controlled by useState() in its dependent parameter.

No comments:

Post a Comment