[React] What is useEffect?

·

3 min read

[React] What is useEffect?

useEffect is a React Hook that lets you synchronize a component with an external system.


How to use useEffect?

useEffect(setup, dependencies?)

import { useEffect, useState } from 'react';
import { createConnection } from './chat.js';

function ChatRoom({ roomId }) {
  const [serverUrl, setServerUrl] = useState('https://localhost:1234');

  useEffect(() => {
    const connection = createConnection(serverUrl, roomId);
    connection.connect();
    // cleanup func
    return () => {
      connection.disconnect();
    };
  }, [serverUrl, roomId]);
  // ...
}

Parameters

  • setup: The function with your Effect’s logic. Your setup function may also optionally return a cleanup function. When your component is added to the DOM, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. After your component is removed from the DOM, React will run your cleanup function.

  • optionaldependencies: The list of all reactive values referenced inside of the setup code. Reactive values include props, state, and all the variables and functions declared directly inside your component body.

    1. Passing a dependency array:

      If you specify the dependencies, your Effect runs after the initial render and after re-renders with changed dependencies.

    2. Passing an empty dependency array:

      If your Effect truly doesn’t use any reactive values, it will only run after the initial render.

    3. Passing no dependency array at all:

      If you pass no dependency array at all, your Effect runs after every single render (and re-render) of your component.

Returns

useEffect returns undefined.


When to use useEffect?

import { useEffect, useState } from 'react';

interface DemoProps {}

export default function Demo({}: DemoProps) {
  const [count, setCount] = useState(0);

  useEffect(() => {
    // The code that we want to run (setup func)
    console.log('The count is:', count);

    // Optional return function (cleanup func)
    return () => {
      console.log('I am being cleaned up!');
    };
  }, [count]); // The dependency array

  return (
    <div className='tutorial'>
      <h1>Count: {count}</h1>
      <button onClick={() => setCount(count - 1)}>
        Decrement
      </button>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  );
}

In this case, everytime you click Increment/Decrement button, first the useEffect hook will destroy itself and run the cleanup function(return function) and then second it's going to be recreated with the new value and run the setup function.

So it will look like this in console:

Before click Increment button

After click Increment button

Cleanup function is more useful when you have timeout in setup function so you need to clear the timeout before you create a new timeout or when you need to remove event listener if you add event listener in setup function.


Reference