Sobes.tech
Junior

How to use the useEffect hook in React?

sobes.tech AI

Answer from AI

useEffect allows performing side effects in functional components.

It takes two arguments:

  1. A function containing the effect code.
  2. An array of dependencies.

Side effects include:

  • Data fetching.
  • Subscriptions.
  • Manual DOM manipulations.
// Example of using useEffect to perform an effect on component mount
useEffect(() => {
  // Effect code: for example, fetching data from an API
  console.log('Component mounted. Loading data...');

  // Cleanup function (optional)
  return () => {
    // Code to clean up resources (e.g., cancel subscriptions) on unmount
    console.log('Component will unmount. Cleaning up...');
  };
}, []); // Empty dependencies array - effect runs once on mount

// Example with dependencies
useEffect(() => {
  // Effect code that depends on the value of a prop or state
  console.log('Value ' + userId + ' changed. Updating user data.');

}, [userId]); // Effect runs on initial render and whenever userId changes

// Example without dependencies array
useEffect(() => {
  // Effect runs on every render of the component
  console.log('Component re-rendered.');
});

Important points:

  • The function passed to useEffect runs after rendering (or after the first render for an empty dependencies array).
  • The cleanup function returned from the effect runs on unmount or before the next effect execution (when dependencies change).
  • The dependencies array controls when the effect should run. An empty array ([]) means once on mount. Including dependencies means the effect runs when they change. No array means it runs on every render.
  • All variables from the component scope used inside the effect that can change over time should be included in the dependencies array.