Custom hooks: How to reset state when inputs are updated?
See original GitHub issueDo you want to request a feature or report a bug?
Probably a feature, I’d like to know why the useState
hook does not have a second argument to compare inputs similar to other hooks.
What is the current behavior?
I’m trying to implement custom hooks for a timer and countdown library that we use at work. However, for this example I would like to describe a more minimal example with a counter that counts up from a provided initial value.
I created a small fiddle with a custom hook useCountUp
that takes an initial value and increments it each second. The counter should reset itself, when the initialValue that is passed to the custom hook changes. As the fiddle demonstrates, it is currently not really possible to reset the state of the useState
hook. As a hack, the hook compares the inputs in a useMemo
function and updates the state in the next useEffect
run. This however, leads to a duplicate render, which would not be necessary.
My question: Why did the useState
hook API not receive a second argument to use reset the state to the provided initalValue when certain inputs change, similar to useMemo
, useEffect
and other hooks? Without this, we need to re-render twice with the same state in this example to ensure that the counter’s state is consistent.
As a comparison, a Component with render props would have no problems with reseting the state when necessary: https://codesandbox.io/s/3vrpnxo2kq
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
React Version: 16.7.0-alpha.2-next
Issue Analytics
- State:
- Created 5 years ago
- Comments:5 (3 by maintainers)
Top GitHub Comments
It’s ignored so it doesn’t matter in practice. React won’t re-render deeply. It will immediately call the render again.
Hmm. I dunno. It seems a bit niche but I kinda like it? Can you file an RFC please? https://github.com/reactjs/rfcs