I am impressed by the expressiveness of React hooks. It feels good when you can do so much by writing so little.

But the brevity of hooks has a price — they’re relatively difficult to get started. This is true for useEffect() — the hook that manages side-effects in React components.

In this post, I wrote a simple and accessible explanation of useEffect().

1. useEffect() is for side-effects

A functional React component uses props and/or state to calculate the output. If the functional component makes calculations that don’t target the output value, then these calculations are named side-effects.

Examples of side-effects are fetching requests, manipulating DOM directly, using timer functions like setTimeout(), and more.

You cannot perform side-effects directly in the body of the functional component. How often the component renders isn’t something you can control — if React wants to render the component, you cannot stop it.

function Greet({ name }) {
  const message = `Hello, ${name}!`; // Calculates output

  // Bad!
  document.title = 'Greetings page'; // Side-effect!

  return <div>{message}</div>;       // Calculates output
}

The component rendering and side-effect invocation have to be independent. Welcome useEffect() — the hook that runs side-effects.

import React, { useEffect } from 'react';

function Greet({ name }) {
  const message = `Hello, ${name}!`;   // Calculates output

  useEffect(() => {
    // Good!
    document.title = 'Greetings page'; // Side-effect!
  }, []);

  return <div>{message}</div>;         // Calculates output
}

useEffect() hook accepts 2 arguments:

useEffect(callback[, dependencies]);
  • callback is the callback function containing side-effect logic. It is invoked after React has committed the changes to the screen.
  • dependencies is an optional array of dependencies. React is going to invoke the callback only when the dependencies have changed between renderings.

dependencies array lets you control when the side-effect runs:

  • Not provided: the side-effect runs after each rendering
  • An empty array []: the side-effect runs once after the initial rendering
  • With props or state values [prop1, prop2, ..., state1, state2]: the side-effect runs only when any value in the dependencies change.

#react #hook #useEffect

A Simple and Accessible Explanation of React.useEffect()
11.95 GEEK