React Hook Lifecycle – control WHEN functions are executed

By defining the dependencies in your #useEffect method, you can control the execution of methods and the rendering.

Execute only once when component is first rendered
By passing an empty array for a #useEffect method, you guarantee that the method is only executed once:

useEffect(() => {
     //do something....
}, [])

Now it behaves like #componentDidMount in the old React class architecture.

Execute after every render cycle
If no array is passed to #useEffect, the method will be executed AFTER EVERY render cycle:

useEffect(() => {
     //do something...
})//no array here

Execute only if some value has changed
If #useEffect shall only be executed when a certain variable has changed, do:

useEffect(() => {
     //do something...
   ...myValue...
}, [myValue])//myValue defined in the array

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.