How to Create Side Effects in React

Certain actions happen outside of the scope of a component, such as fetching data from external API, reading or writing from the file system, modifying the DOM tree manually, and so on. These actions are referred to as side effects.

useEffect() is a React hook that allows you to write side effects inside React components, providing a portal to the outside of the application. It is most commonly used to synchronize the component with external systems.

Basic syntax

The useEffect() hook accepts a callback function. By default, this function will be executed after every render.

jsx
1useEffect(() => {
2  // Perform some action here
3});

This default behavior may lead to problems, especially when the side effect is resource-intensive, and you want to avoid unnecessary reruns. In this case, you can modify the default behavior by defining a dependency array.

If an empty array is provided, the function will be executed only once after the component is mounted (when the component first appears).

jsx
1useEffect(() => {
2  // Perform some action here
3}, []);

However, if you specify dependencies in the array, which are usually reactive variables such as props and states, the function will re-execute when the dependencies change.

jsx
1useEffect(() => {
2  // Perform some action here
3}, [count]); // The callback function will be executed every time "count" changes

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

šŸŽ‰ Create an Account šŸŽ‰