assigning a function to a `useState` variable
Personne n'a encore pris cette issue.
- Langage dominant
- JavaScript
- Étoiles
- 11.8k
- Forks
- 7.9k
- Merge moyen
- 1 j 11 h
- PR mergées (30 j)
- 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!
Guide de contribution
Ouvrir le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Piste de recherche
Commencez par localiser la section de la documentation de React Hooks pertinente pour useState et useEffect. Documentez le comportement présenté dans l’issue : stocker une fonction dans le state nécessite un callback updater qui retourne la fonction, et expliquez le cas d’utilisation du setup et du cleanup. Le travail est terminé lorsque les explications sont placées sur une page Hooks appropriée et couvrent clairement pourquoi le fait de passer directement la fonction l’invoque.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- javascript, react
- Domaine
- documentation
- Type d'issue
- Documentation
- Difficulté
- 3/5
- Temps estimé
- 1-2 jours
- Activité
- À l'abandon
- Clarté
- Plutôt claire
- Accessibilité débutants
- 45/100