Categories
React

[Hook] – useEffect

  1. Pure Function VS Side Effect
  2. useEffect
  3. How do I use useEffect?
  4. Common mistakes
  5. Cleanup function
  6. Refs

Pure Function VS Side Effect

  • Most React components are pure functions, meaning they receive an input and produce a predictable output of JSX
    • The same input, it will always return the same output
    • Predictable, reliable, and easy to test
  • Side effects are not predictable because they are actions which are performed with the “outside world.”
  • Common side effects include:
    • Making a request to an API for data from a backend server
    • To interact with browser APIs (that is, to use document or window directly)
    • Using unpredictable timing functions like setTimeout or setInterval

useEffect

  • To provide a way to handle performing these side effects
  • Side effects should be separated from the rendering process, it should strictly be done after our component renders
  • If we perform a side effect directly in our component body, it gets in the way of our React component’s rendering

How do I use useEffect?

// 1. import useEffect
import { useEffect } from 'react';

function MyComponent() {
  // 2. call it above the returned JSX  
  // 3. pass two arguments to it: a function and an array
  useEffect(() => {}, []);
  
  // return ...
}

The function passed to useEffect is a callback function. This will be called after the component renders.

The second argument is an array, called the dependencies array. This array should include all of the values that our side effect relies upon.


Common mistakes

  • Undefined dependencies array -> function will run after every render -> may cause infinite loop
  • Empty dependencies array -> only run once after the component has rendered the first time
    • To fetch data

Cleanup function

  • To shut off side effects
    • Stop setInterval countdown timer
    • “Turn off” subscriptions with WebSockets
// Before
function Timer() {
  const [time, setTime] = useState(0);
    
  useEffect(() => {
    setInterval(() => setTime(1), 1000); 
    // counts up 1 every second
    // we need to stop using setInterval when component unmounts
  }, []);
}

// After
function Timer() {
  const [time, setTime] = useState(0);
    
  useEffect(() => {
    let interval = setInterval(() => setTime(1), 1000); 

    return () => {
      // setInterval cleared when component unmounts
      clearInterval(interval);
    }
  }, []);
}

The problem before adding cleanup function with this if the component is destroying, is that setInterval will try to update a variable a piece of state time that no longer exists. This is an error called a memory leak.


Refs

https://www.freecodecamp.org/news/react-useeffect-absolute-beginners

Leave a comment