iTranslated by AI
Tips for Managing Functions in React Hooks useState
React hooks' useState is an important function that holds state just like traditional state management.
For example, a simple counter would look like this:
const useCounter = () => {
const [count, setCounter] = useState(0)
return { count, setCounter }
}
export const MyApp = () => {
const { count, setCounter } = useCounter()
return (
<div>
<div>{count}</div>
<button onClick={() => setCounter(count + 1)}>+</button>
</div>
)
}
If you want to store a function in this useState, you need to be a bit careful.
For example, if you write it like this, it will result in unintended behavior.
const initialHelloFn = () => {
console.log("initial")
}
const useCounter = () => {
const [count, setCounter] = useState(0)
const [helloFn, setHelloFn] = useState(initialHelloFn)
// This newFn will be called repeatedly
const newFn = useCallback(() => {
console.log("hello!", count)
}, [count])
useEffect(() => {
setHelloFn(newFn)
}, [newFn, setHelloFn])
console.log(helloFn)
return {
count,
setCounter,
helloFn
}
}
export const MyApp = () => {
const { count, setCounter, helloFn } = useCounter()
return (
<div>
<div>{count}</div>
<button onClick={() => setCounter(count + 1)}>+</button>
<button onClick={() => helloFn()}>hello</button>
</div>
)
}
Doing this will likely result in a large volume of output like hello! 0.
How to make it work correctly?
Manage it as an object, like {fn: functionToManage}.
const useCounter = () => {
const [count, setCounter] = useState(0)
// Wrap it in an object like {fn: Function}
const [helloFn, setHelloFn] = useState({ fn: initialHelloFn })
const newFn = useCallback(() => {
console.log("hello!", count)
}, [count])
useEffect(() => {
setHelloFn({ fn: newFn })
}, [newFn, setHelloFn])
return {
count,
setCounter,
helloFn: helloFn.fn
}
}
Why is this necessary?
In short, handlers like setFoo returned by useState support Functional Updates, so if you pass a function directly, it will be processed as a Functional Update.
Functional Updates themselves are convenient because they allow you to work with just a function without inheriting the current value, as shown below:
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
This isn't new to hooks; a similar feature existed in React.Component.setState as well.
However, in the case of Component, state itself is an object, so people rarely ran into this issue. Since useState can be used to store simple values, this is something you should be careful about.
Discussion
なるほど!