assigning a function to a `useState` variable
Ninguém assumiu esta issue ainda.
- Linguagem predominante
- JavaScript
- Estrelas
- 11.8k
- Forks
- 7.9k
- Merge médio
- 1d 11h
- PRs com merge (30d)
- 11
Descrição
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!
Guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Direção de pesquisa
Comece localizando a seção da documentação de React Hooks relevante para useState e useEffect. Documente o comportamento mostrado na issue: armazenar uma função no state requer um callback updater que retorne a função, e explique o caso de uso de setup e cleanup. A tarefa estará concluída quando a orientação estiver colocada em uma página apropriada de Hooks e explicar claramente por que passar a função diretamente a invoca.
Escrita pelo modelo de indexação a partir do texto da issue.
Avaliação
- Stack de tecnologia
- javascript, react
- Domínio
- documentation
- Tipo de issue
- Documentação
- Dificuldade
- 3/5
- Tempo estimado
- 1-2 dias
- Status de atividade
- Estagnada
- Clareza
- Razoavelmente clara
- Facilidade para iniciantes
- 45/100