DEV Community

Cover image for React.js ~useEffect for synchronizing an external system~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

React.js ~useEffect for synchronizing an external system~

In React, useEffect is a hook that is used to synchronize an external system.

What is an external system ?
The external system here indicates an system that isn't controled by React. Such as

  • Network
  • Browser API
  • Third party library or widegt

These systems are out side of React, and isolated from React's state management or life cycle.

synchronization between component and external system
There is a specific component that synchronizes an external system in components.

Let's consider a <Clock /> that dusplays the current time.

synchronizing component and the current time is not a pure calculation. So,

You must not write the code below;

// Bad: Get the current time during rendering.
const Clock = () => {
  // new Date() is not pure.
  const dateTime = new Date();
  return <div>{dateTime.toLocaleString()}</p>;
};

In the light of the above, implementing the `<Clock />` is follows;

Enter fullscreen mode Exit fullscreen mode

Furthermore, synchronization of the current time should occur as part of the component's rendering, regardless of user interaction; this is what is known as an effect.

// Good: Getting current time runs in the effect
const Clock = () => {
  const [dateTime, setDateTime] = useState(() => new Date());

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

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

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

Enter fullscreen mode Exit fullscreen mode

As such, You can synchronize a component and an external system by using useEffect.

Starting and stop synchronization
When you synchronize useEffect and external system, effect can be considered as a process of synchronization.

Basicly, things that effect does are follows;

  • Start synchronization.
  • Stop synchronization.

In many cases, you have to take stopping into considerstion. Because useEffect needs to restore an effect when unmounting a component.

useEffect(() => {
  // Start
  const id = setInterval(() => {
    setTime(new Date());
  }, 1000);

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

Enter fullscreen mode Exit fullscreen mode

In this effect, things goes as follows;

1.Starting a synchronization: Updating current time starts by using setInterval. This is connecting to an external system.

2.Stopping a synchronization: You call clearInterval by using a clean up function. This is disconnection an external system.

Top comments (0)