batched-hook
Batched set state and dispatch for react hooks
Problem
Sometimes state updates caused by multiple calls to useState setter, are not batched. more detail
Example:
{ const count setCounter = ; { ; } return count inc;} { const a incA = ; const b incB = ; const renderCount = ; renderCountcurrent = renderCountcurrent + 1; console; ; const incAll = ; ; return <div ="App"> render count: <div ="count">renderCountcurrent</div> state: <div ="state"> a-b </div> <button ="button" => increment all </button> </div> ;}
output:
render1 0 0
effect 0 0
// click
render2 1 0 <-- bad render
effect 1 0 <-- bad effect
render3 1 1
effect 1 1
Solution
with batched-hook
you can batch calls to dispatch
of useReducer
and setter of useState
hooks.
render1 0 0
effect 0 0
// click
render2 1 1
effect 1 1
Install
yarn add batched-hook
Usage
;;; // `uninstall` function will restore default React behavior.const uninstall = ;
How it works
install
function patches React and replace useState
and useReducer
with new functions. These functions have the
same functionality but when you call dispatch
, the called function and its arguments will be saved into a queue. after
all sync statements, all function calls inside the queue we will be called inside ReactDOM.unstable_batchedUpdates
.