iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐈

When Should You Actually Use useEffect?

に公開
2024/08/20

useEffect is known as one of the more challenging hooks in React. Many developers have likely struggled with when to consider using useEffect and how to use it appropriately during development.

In this article, I would like to explore the purpose of useEffect and consider when you should actually consider using it.

Component Purity and Side Effects

Before thinking about useEffect, we must understand component purity. Purity is one of the most important concepts in React.

As a premise, React assumes that every component you write is a pure function.

React assumes that every component you write is a pure function.
Reference: https://react.dev/learn/keeping-components-pure#purity-components-as-formulas

A pure function is a function that only performs calculations and does nothing else. Pure functions have the following characteristics:

  • It minds its own business. It does not change any objects or variables that existed before it was called.
  • Same inputs, same output. Given the same inputs, a pure function should always return the same result.

Reference: https://react.dev/learn/keeping-components-pure#purity-components-as-formulas

In React, since components are also functions, we can apply the characteristics of pure functions mentioned above to components. Therefore, a pure component can be said to have the following characteristics:

  • It is idempotent.
  • It has no side effects during rendering.
  • It does not modify anything other than local values.

As a rule, components should be pure. This means that in React, components should not affect anything outside of themselves and must always return the same output if the inputs are the same.

For example, the following code is an example of a pure component:

Example of a pure component
const Counter = ({ count }: { count: number }) => {
  return <div>Count: {count}</div>;
};

The component above receives an input (Props) called count and displays it. This is a pure component, so if the same count is provided as input (Props), it will always return the same output.

On the other hand, the following code is not a pure component:

Example of an impure component
let count = 0;

const Counter = () => {
  count = count + 1;
  return <div>Count: {count}</div>;
};

The component above modifies a count variable outside the component during rendering. Therefore, if you call the component multiple times, the output will differ even though the inputs are the same.

Such impure components can cause unexpected behavior and bugs, so they should be avoided.

As we have seen so far, purity is an important concept in React. However, in actual programming, you may need side effects such as accessing global variables, modifying the DOM, or updating data.

The component rendering process should always be pure, but you cannot completely eliminate side effects while programming. Therefore, you need a way to safely handle side effects while keeping rendering pure.

React provides two main ways to safely handle side effects:

  1. Event Handlers: Functions that React calls when a user action is performed.
  2. useEffect: A React hook for handling side effects associated with rendering.

Among the above, side effects usually belong in event handlers. Since this article focuses on useEffect, I will not go into detail about event handlers, but please note that useEffect is by no means better than event handlers as a place to handle side effects.

Instead, please remember that useEffect is an escape hatch.

What are Effects?

As mentioned above, React rendering should be pure. You should not include side effects within render. This principle is explicitly stated as a rule of React.

Side effects must not run during render.
Reference: https://react.dev/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render

If some side effect occurs due to a user action, you can keep rendering pure by writing the side effect in an event handler. By using an event handler, you can tell React that the code does not need to be executed during rendering.

However, not all side effects are caused by an event. That is where Effects come in.

Effects are for specifying side effects that are caused by rendering itself, rather than by a particular event.
Reference: https://react.dev/learn/synchronizing-with-effects#what-are-effects-and-how-are-they-different-from-events

useEffect, as the name suggests, is a hook for handling effects. React uses useEffect as a marker for effects.

Effects are side effects caused by rendering, not by events. Therefore, useEffect decouples rendering from the effect, delaying the execution of code until the render result is reflected on the screen (after committing).

By using useEffect, you can handle effects appropriately while keeping rendering pure.

useEffect synchronizes components with external systems

Now that we have confirmed the concept of effects, let's think about situations where effects are necessary.

React's useEffect hook is used to synchronize a component with an external system. The official documentation describes it as follows:

useEffect is a React Hook that lets you synchronize a component with an external system.
Reference: https://react.dev/reference/react/useEffect

What is an external system?

An "external system" here refers to a system not controlled by React. Specifically, things like the following apply:

  • Network
  • Some browser APIs
  • Third-party libraries or widgets

These systems are outside of React and operate independently of React's state management and rendering cycles.

Synchronizing components with external systems

Some components need to be synchronized with an external system as long as they are displayed on the screen.

For example, consider a <Clock> component that displays the time in real-time.

Synchronizing a component with the current time is not a pure calculation, so it should not be done during rendering. The following code is an example of an implementation that should not be done.

Performing impure processing during render
// Bad: Getting current time during render
const Clock = () => {
  // new Date() is not idempotent and not pure
  const dateTime = new Date();
  return <div>{dateTime.toLocaleString()}</div>;
};

Furthermore, synchronization with the current time should accompany the component's rendering regardless of user interaction, which means it is an effect.

Based on the above, let's implement the <Clock> component:

Performing impure processing in an effect
// Good: Synchronize current time in an effect
const Clock = () => {
  const [dateTime, setDateTime] = useState(() => new Date());

  // Synchronizing current time is implemented as an effect
  useEffect(() => {
    const id = setInterval(() => {
      setDateTime(new Date());
    }, 1000);

    // Cleanup
    return () => {
      clearInterval(id);
    };
  }, []);

  return <div>{dateTime.toLocaleString()}</div>;
};

By using useEffect in this way, you can synchronize a component with an external system.

Starting and stopping synchronization

When using useEffect to synchronize a component with an external system, you can think of the effect as a synchronization process.

Basically, an effect does the following two things:

  1. Start synchronization (connect to an external system)
  2. Stop synchronization (disconnect from an external system)

It is easy to forget, but in many cases, stopping synchronization is also necessary. This is because the processing executed in useEffect must revert its effects when the component is unmounted.

Let's re-examine the useEffect of the <Clock> component from earlier.

Starting and stopping synchronization
useEffect(() => {
  // Start synchronization (connect)
  const id = setInterval(() => {
    setTime(new Date());
  }, 1000);

  // Stop synchronization (disconnect)
  return () => {
    clearInterval(id);
  };
}, []);

In this effect, the following occurs:

  1. Start synchronization: Start updating the time using setInterval. This corresponds to "connecting" to the external system.
  2. Stop synchronization: Call clearInterval in the cleanup function. This corresponds to "disconnecting".

React cleans up the previous effect and executes a new effect every time the component re-renders or whenever the values specified in the dependency array change. This ensures that the effect's synchronization process is carried out correctly.

In this article, I will not discuss the lifecycle of effects further, but if you want to learn more, please refer to "Lifecycle of Reactive Effects – React".

Conclusion

As mentioned at the beginning, useEffect is one of the more difficult hooks to handle in React. Even if you read the official documentation, the descriptions cover a wide range of topics, and it may take time to master.

React's official documentation also introduces anti-patterns, starting with "You Might Not Need an Effect – React". When using useEffect, it is important to always consider whether the effect is truly necessary and whether it can be achieved in a more appropriate way.

I hope this article helps you.

References

https://react.dev/reference/react/useEffect
https://react.dev/learn/synchronizing-with-effects
https://react.dev/learn/you-might-not-need-an-effect
https://react.dev/learn/keeping-components-pure
https://react.dev/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render
https://react.dev/learn/lifecycle-of-reactive-effects
https://overreacted.io/a-complete-guide-to-useeffect/

https://zenn.dev/uhyo/articles/useeffect-taught-by-extremist
https://zenn.dev/yumemi_inc/articles/react-effect-simply-explained

Discussion