DEV Community

Rakshambika
Rakshambika

Posted on

useEffect in React

What is useEffect?

useEffect is a React Hook that runs code after a component renders.

Some common use cases are:

  • Fetching data from an API
  • Updating the document title
  • Working with localStorage
  • Setting up timers
  • Adding event listeners

Syntax

import { useEffect } from "react";

useEffect(() => {
  // Code
}, []);

Enter fullscreen mode Exit fullscreen mode
  • The first argument is a function containing the code we want to execute.
  • The second argument is called the dependency array.

useEffect with an Empty Dependency Array

import { useEffect } from "react";

function App() {
  useEffect(() => {
    console.log("Component with Empty Dependency Array");
  }, []);

  return <h1>Hello React</h1>;
}
Enter fullscreen mode Exit fullscreen mode

Output

Component with Empty Dependency Array
Enter fullscreen mode Exit fullscreen mode

This effect runs only once when the component is first rendered.


useEffect with Dependencies

import { useState, useEffect } from "react";

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

  useEffect(() => {
    console.log("Count Changed");
  }, [count]);

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

Whenever count changes, the effect runs again.

Output

Count Changed
Enter fullscreen mode Exit fullscreen mode

This is useful when we want to perform an action whenever a specific state value changes.


useEffect Without Dependency Array

useEffect(() => {
  console.log("Runs After Every Render");
});
Enter fullscreen mode Exit fullscreen mode

Since there is no dependency array, the effect runs after every render.

Be careful when using this because unnecessary executions can affect performance.


Top comments (0)