DEV Community

SATHISHKUMAR R
SATHISHKUMAR R

Posted on

What is useEffect in React?

useEffect is a React Hook used to perform side effects in a functional component.

It is commonly used for:

  1. Fetching API data.
  2. Updating the document title.
  3. Using timers (setTimeout, setInterval).
  4. Adding event listeners.
  5. Running code when a component loads or when state changes.

  6. useEffect syntax:

import { useEffect } from 'react';

useEffect(() => {

}, []);

  1. Example: useEffect:

import React, { useState, useEffect } from 'react';

function App() {

const [count, setCount] = useState(0);

useEffect(() => {
    console.log("Component Loaded");
}, []);

return (
    <div>
        <h1>Count: {count}</h1>

        <button onClick={() => setCount(count + 1)}>
            Click Me
        </button>
    </div>
);
Enter fullscreen mode Exit fullscreen mode

}

export default App;

Output:

  • When the component loads → Component Loaded
  • When you click the button → Count increases.
  • The effect does not run again because the dependency array is empty.
  • Three types of useEffect:

Type 1: Without dependency array:

useEffect(() => {
console.log("Runs after every render");
Enter fullscreen mode Exit fullscreen mode

});

Runs after every render.

Type 2: Empty dependency array :

useEffect(() => {
console.log("Runs after initial mount");
Enter fullscreen mode Exit fullscreen mode

}, []);

Runs after the component mounts (in development Strict Mode, React may run an extra setup cycle).

Type 3: With dependency:

useEffect(() => {
console.log("Count changed");
Enter fullscreen mode Exit fullscreen mode

}, [count]);

Runs when count changes.

Top comments (0)