Why React useState with functional update form is needed?

后端 未结 4 810
庸人自扰
庸人自扰 2020-12-18 00:28

I\'m reading React Hook documentation about functional updates and see this quote:

The ”+” and ”-” buttons use the functional form, because the updat

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 00:52

    Another use case for using functional updates with setState - requestAnimationFrame with react hooks. Detailed information is available here - https://css-tricks.com/using-requestanimationframe-with-react-hooks/

    In summary, handler for requestAnimationFrame gets called frequently resulting in incorrect count value, when you do setCount(count+delta). On the other hand, using setCount(prevCount => prevCount + delta) yields correct value.

提交回复
热议问题