useEffect Hook

  • use to call API
  • this hook is meant for side effects
  • takes a function and an array
  • happens outside of rendering
  • can do all componentDidMount(), componentWillMount(), componentWillUnMount(), & class components
  • can not do error boundaries
  • can use async/await but need to do it inside the function
    • can do async on the function call because it turns it into a promise,
    • useEffect function has to be immediately invokable or else react will complain
const [pokemon, setPokemon] = useState('pikachu')
useEffect(() => {
document.title = `Go ${pokemon}!`
}, [pokemon])
  • tell function to stay in sync with the pokemon variable
  • doesn't have to be a state variable; can be any declared variable

When useEffect run?

  • on initial render
  • on every single state change
  • dependency array (optional parameter) controls when useEffect is called:
    • [someVar] - effect is run on initial render, and when var changes
    • [] - effecit is run on initial render only
    • nothing - run on initial render AND every state change
  • Can further control by adding if statements in the function
  • dependency array can have as many things inside as you want
useEffect(() => {
let isCurrent = true
fetch(`https://pokeapi.co/api/v2/pokemon/${pokemon}/`)
.then((res) => res.json())
.then((res) => {
if(isCurrent) { // simple guard rail to make sure effect is the most up to date
setPokemon(res.name)
setImg(res.sprites.front_default)
}
})
.catch((error) => {
setError(error)
})
return () => { // clean up function
isCurrent = false
}
}, [pokemon, img, error])

Clean up function

  • when component dismounts, when values changes in dependency array, return value is called
  • same as componentWillUnMount
  • clean up function is where you would turn off eventListener1
useEffect(() => {
// 2. This function body is your effect
window.addEventListener("resize", handleResize)
return () => {
// 1. Optionally clean up effects inside this function
window.removeEventListener("resize", handleResize)
}
}, []) // 3. Conditionally execute based on dependencies array