The useEffect Hook
Side Effects: an operation, function or expression is said to have a side effect if it modifies some state variable value(s) outside its local environment, while having an observable effect besides returning a value. (Wikipedia on Side Effects)
Side Effects are used to make network requests, accessing data from a data base, writing to the file system, etc.
Use the useEffect hook to handle side effects in components
import React, {useEffect} from 'react'
function App() {
useEffect(() => {
console.log('useEffect called')
}
)
console.log('component rendered')
}
In the above example, if you run the code, the "component rendered" log will display first and then the 'useEffect Called'. This shows that everytime your compnent renders, the useEffect will be called.
- By using this hook, you tell react that the component has to do something after rendering.
Dependencies Array
In certain situations, you don't want your useEffect to execute everytime the component re-renders.
The dependencies array is a way to control hen the side effect will run by passing a second argument to useEffect
examples:
//example 1 useEffect( ()=> console.log("useEffect Called"), [count] //you can put a state variable or any variable. This effect //will only take place when the count variable is changed. ) //example 2 useEffect(()=> { fetch("Some API") .then((r)=> r.json()) .then((data) => { setImages(data.message) }); }, []; //When you put an empty dependancy array, the useEffect //will only occur once
useEffect Dependancies Cheatsheet
useEffect(()=> {}) : No dependancies Array
- run this side effect EVERYTIME our component render
useEffect(()=> {}, []) : Empty dependancies array
- run this side effect only the first time the component renders
useEffect(()=> {}, [variable1, variable2]): Dependancies array with elements in it
- Run this side effect any time the variable(s) changes
citations
- flatiron school