assigning a function to a `useState` variable
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 11.8k
- Forks
- 7.9k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 11
Description
I was toying with storing a function in a useState variable, like this:
const behavior = () => {
// set something up
return () => {
// tear it back down
}
}
// inside the component
const [cleanupFunction, setCleanupFunction] = useState(null)
useEffect(() => {
if (behavior){
const cleanup = behavior()
setCleanupFunction( () => cleanup )
} else {
cleanupFunction && cleanupFunction()
}
}, [behavior])
This pattern is great for when you want to set up and tear down behavior when a prop changes, rather than wait until unmount. You can imagine that different behaviors with their associated cleanups can be passed in.
I was initially tempted to say setCleanupFunction(cleaup), but this was not working - my function was being called without me explicitly calling it. This explanation on stackoverflow gives a crucial tidbit: when storing a callback as a useState variable, it must be stored as a callback function which returns the function you want to call. I feel this use case should be somewhere in the react docs in the hooks section.
Thank you for everything you do!
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by locating the React Hooks documentation section relevant to useState and useEffect. Document the behavior shown in the issue: storing a function in state requires an updater callback that returns the function, and explain the setup and cleanup use case. Done when the guidance is placed in an appropriate Hooks page and clearly covers why directly passing the function invokes it.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, react
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100