reactjs / reactjs/react.dev

assigning a function to a `useState` variable

Aperta
#3,297 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Lingua principale
JavaScript
Stelle
11.8k
Fork
7.9k
Merge medio
1g 11h
PR unite (30g)
11

Descrizione

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!

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia individuando la sezione della documentazione di React Hooks pertinente per useState e useEffect. Documenta il comportamento mostrato nell’issue: memorizzare una funzione nello state richiede un callback updater che restituisca la funzione, e spiega il caso d’uso di setup e cleanup. Il lavoro è completato quando la guida è collocata in una pagina Hooks appropriata e spiega chiaramente perché passare direttamente la funzione la invoca.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
javascript, react
Ambito
documentation
Tipo di issue
Documentazione
Difficoltà
3/5
Tempo stimato
1-2 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.