useeffect how to know what changed

Understanding useEffect Changes: A Guide

By Nicole Walker
AD

Understanding how to use the useEffect hook in React is crucial for managing side effects in functional components. A common question arises: how do you know what changed when dealing with multiple dependencies and effect functions? This article will guide you through deciphering what changes when using useEffect and optimizing your code for better performance.

Before diving into the details, let's recap what useEffect does. It's a React hook that lets you run side effects from your components, such as data fetching, subscriptions, timers, logging, and more. It accepts two arguments: a callback function (the effect) and an optional array of dependencies.

Tracking Changes with useEffect

The useEffect hook runs whenever one of its dependencies changes. To track changes, you must first understand how React determines when to re-run an effect:

AD
Affect vs. Effect: What’s the Difference? (Simple Guide!)
Affect vs. Effect: What’s the Difference? (Simple Guide!)
How to Test One Focus Change at a Time
How to Test One Focus Change at a Time
The "Google Effect" - How offloading memory to smartphones is changing how our brains store and retrieve information. #positivepsychology #selflove❤️ #ᴛʀᴇɴᴅɪɴɢɴᴏᴡ #cartoonstyle
The "Google Effect" - How offloading memory to smartphones is changing how our brains store and retrieve information. #positivepsychology #selflove❤️ #ᴛʀᴇɴᴅɪɴɢɴᴏᴡ #cartoonstyle

  • No dependencies ([]): The effect runs after every render, even if no changes occurred. This could lead to unnecessary re-runs and performance issues.
  • With dependencies ([dependency]): The effect only runs when the specified dependency (or dependencies) changes.

Nine Ways an Interface Changes Its Own Evidence
Nine Ways an Interface Changes Its Own Evidence
Affect or Effect? Choose by Job and Meaning
Affect or Effect? Choose by Job and Meaning
a piece of paper that has some type of writing on it with the words effect
a piece of paper that has some type of writing on it with the words effect

Dependency Arrays

The dependency array is critical for tracking changes. When using it, React maintains a reference to the values of the dependencies every time you render. If the values change between renders, React re-runs the effect. Here's an example:

AD
  import React, { useState, useEffect } from 'react';

  function Counter() {
    const [count, setCount] = useState(0);
    const [ braindump, setBrainDump] = useState('initial braindump');

    useEffect(() => {
      console.log(`You changed: ${count}, ${braindump}`);
    }, [count, braindump]);

    return (
      <div>
        <p>Count: {count}</p>
        <button onClick={() => setCount(c => c + 1)}>Increment</button>
        <p>Brain dump: {braindump}</p>
        <button onClick={() => setBrainDump('new braindump')}>Change Brain dump</button>
      </div>
    );
  }

an image with the words to know if what you're doing is effective, you have to know what effect you're trying to create
an image with the words to know if what you're doing is effective, you have to know what effect you're trying to create
Master Lewin's Change Management Model: Unfreeze, Change, Refreeze
Master Lewin's Change Management Model: Unfreeze, Change, Refreeze
Information Isn't Transformation: How to Create Real Personal Change
Information Isn't Transformation: How to Create Real Personal Change
Affect vs Effect 🍁 জেনে নিন কোনটা কখন ব্যবহার করবেন! #english #grammar #spokenenglish
Affect vs Effect 🍁 জেনে নিন কোনটা কখন ব্যবহার করবেন! #english #grammar #spokenenglish
a black and white photo with the words 11 home hacks that will actually change your life
a black and white photo with the words 11 home hacks that will actually change your life
a poster with instructions for how to use the english language
a poster with instructions for how to use the english language

The useEffect hook in this example will only run when either count or braindump changes, as specified in the dependency array.

In-depth Dependency Tracking

If the dependency is an object or an array, React tracks its reference, not its contents. This means you should memoize the value passed to the dependency array when possible:

AD

an old behavior poster with the text how to delete an old behavior
an old behavior poster with the text how to delete an old behavior
Difference between Affect and Effect
Difference between Affect and Effect
The Question to Ask Before Changing Anything in Your Shopify Store
The Question to Ask Before Changing Anything in Your Shopify Store
  function FriendStatus(props) {
    const [isOnline, setIsOnline] = useState(null);

    useEffect(() => {
      function handleStatusChange(status) {
        setIsOnline(status.isOnline);
      }

      ChatAPI.subscribeToUser(props.user.id, handleStatusChange);
      return () => {
        ChatAPI.unsubscribeFromUser(props.user.id, handleStatusChange);
      };
    });

    if (isOnline === null) {
      return 'Loading...';
    }

    return isOnline ? 'Online' : 'Offline';
  }

Here, useEffect relies on the user.id reference for tracking changes, and the returned function from useEffect ensures cleanup when the component unmounts.

AD

Optimizing useEffect for Performance

Optimizing useEffect is crucial for preventing unnecessary re-runs and improving performance. Consider the following techniques:

  • Running cleanup: Always clean up subscriptions, timers, or other side effects when the component unmounts using the returned function from useEffect.
  • Avoid re-runs: Structure your component to avoid unnecessary useEffect re-runs. For instance, use memoized values for dependencies or useEffect Without the dependency array when not needed.
  • Tracking with optional parameters: Sometimes you don't need to track every dependency. You can pass optional parameters to the effect function and check them manually for changes:

        useEffect(() => {
          function handleStatusChange(status) {
            if (status.id !== user.id) return;
            setIsOnline(status.isOnline);
          }
        });
      

useEffect cleanup: Unmounting and Updating

Cleanup functions are essential for managing side effects and preventing memory leaks. useEffect runs the cleanup function in two scenarios:

  • Component unmounts: useEffect's returned function runs whenever the component unmounts to clean up active side effects, like timers or subscriptions.
  • Component mounts & remounts: useEffect performs cleanup before running the effect again when component updates with new dependencies, ensuring a clean state.

Example of a cleanup function for a timer:

  useEffect(() => {
    const timerId = setTimeout(() => {
      console.log('Hello, world!');
    }, 1000);

    return () => clearTimeout(timerId);
  }, []);

The cleanup function (returned function) waits for the component to unmount before clearing the timeout.

Sequential and Concurrent Effects

By default, useEffect mounts synchronously with the render, which means it might not run until the browser has painted the component. If you need to run an effect concurrently, you can wrap it in ReactDOM.unstable_blockPromises:

  ReactDOM.unstable_blockPromises(() => {
    useEffect(async () => {
      const timerId = setTimeout(() => {
        console.log('Hello, world!');
      }, 1000);

      return () => clearTimeout(timerId);
    }, []);
  });

For sequential effects that must run after component mount, use a callback:

  ReactDOM.unstable compatRenderSubtree = hitTest;

While these features are still experimental, they help handle side effects more effectively in certain scenarios.

Understanding and optimizing the useEffect hook is crucial for building efficient and performant React applications. By tracking changes, cleaning up side effects, and leveraging optional features, you can ensure well-maintained and high-functioning components. Happy coding!

AD