Open ypresto opened 5 years ago
This is standard react hooks behavior — your count
variable is closed-over when creating your decrement
behavior. In this case you probably want to use the reducer form of setState
or just use useReducer
directly.
You'll also want to wrap those callbacks in useCallback
to avoid unnecessary re-renders.
function useCounter(initialState = 0) {
const [count, setCount] = useState(initialState)
const decrement = useCallback(() => setCount(count => count + 1), [])
const increment = useCallback(() => setCount(count => count + 1), [])
return { count, decrement, increment }
}
The answer by @shrugs should be added to the official documentation. I think there are also cases where decrement
and increment
should just have their own context, without count
. That's similar to how useReducer is recommended with context.
https://reactjs.org/docs/hooks-faq.html#how-to-avoid-passing-callbacks-down
then
For example, this could be caused by immediate error callback of API client.
Maybe related: #26