ReasonJun

React : useEffect (Hook) 본문

Frontend/React

React : useEffect (Hook)

ReasonJun 2023. 6. 13. 12:10
728x90

In React, useEffect is a hook that allows you to perform side effects in functional components. Side effects can include fetching data from an API, subscribing to events, manipulating the DOM, and more. The useEffect hook is similar to lifecycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount in class components.

 

The useEffect hook takes two arguments: a function and an optional dependency array.

  1. Function: The first argument is the function that will be executed when the component mounts (or updates, depending on the dependencies). This function can include the side effects you want to perform. It may also return a cleanup function that will be executed when the component unmounts or before the next effect runs.
  2. Dependency Array (optional): The second argument is an array of dependencies. It specifies which values the effect depends on. If any of the dependencies change between renders, the effect function will be re-executed. If the dependency array is omitted, the effect runs after every render.
import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // Side effect code here
    console.log('Component mounted or updated');

    return () => {
      // Cleanup code here (optional)
      console.log('Component unmounted or updated');
    };
  }, []); // Empty dependency array means the effect runs only once on mount

  return <div>My Component</div>;
}

In this example, the useEffect hook is used inside the MyComponent functional component. The effect function is defined as an arrow function and logs a message to the console. The cleanup function is also defined as an arrow function and logs a different message.

 

By passing an empty array as the dependency, the effect will only run once when the component mounts. If you include dependencies in the array, the effect will run whenever any of those dependencies change.

useEffect provides a flexible way to handle side effects in React components while ensuring proper cleanup when the component unmounts or before the next effect runs.

728x90
Comments