DEV Community

Cover image for React.js ~useEffect~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

React.js ~useEffect~

Before thinking about useEffect, you have to understand purelity of component. This is an essential concept of React.

React is assumed as a pure function.

The pure function is the function that does nothing but calculation.
Here are features bellow:

  • Focuses on it's own bussiness. This doesn't modify existing object or valuable.

  • The same input produces the same output.Given the same input, a pure function always returns the same result.

React component is a function as well. you can apply those features to React component.

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

As a general rule, components should be pure. In React, this means that components do not affect anything outside the component and must always return the same output given the same input.

The inputs for a React component are props, state, and context, and the output is JSX.

const Counter = ({ count }: { count: nubmer }) => {
  return <div>Count: {count}</div>;
};
Enter fullscreen mode Exit fullscreen mode

The component above is a simple component that accepts an input (prop) called count and displays it. Since this is a pure component, it always returns the same output when given the same count as an input (prop).
On the other hand, the following code is not a pure component.

let count = 0;

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

Enter fullscreen mode Exit fullscreen mode

The component above modifies the count variable outside the component during rendering. As a result, if the component is called multiple times, the output will differ even though the input remains the same.
Such impure components can cause unexpected behavior and lead to bugs, so they should be avoided.
As we’ve seen so far, purity is an important concept in React. However, in real-world programming, side effects—such as accessing global variables, modifying the DOM, or updating data—are sometimes necessary.
While the component rendering process should always be pure, it’s impossible to completely eliminate side effects in programming. Therefore, we need a way to safely handle side effects while keeping the rendering process pure.

React provides two main methods for safely handling side effects:

  • Event handlers: Functions that React calls when a user action is triggered

  • useEffect: A React hook for handling side effects associated with rendering

Of the two, side effects typically belong in event handlers. Since this article focuses on useEffect, we won’t go into detail about event handlers here, but that doesn’t mean useEffect is inherently superior to event handlers for handling side effects.
Instead, keep in mind that useEffect is a last resort.

Top comments (0)