React useEffect Hook – Explained with Example


⚛️ React useEffect Hook – Explained with Example


๐Ÿ“Œ What is useEffect?

The useEffect Hook lets you perform side effects in function components.

๐Ÿง  Side effects include:

  • Data fetching

  • Subscriptions

  • Timer functions

  • Manual DOM manipulations

  • Logging


๐Ÿงพ Syntax

useEffect(<callback>, <dependencyArray>);
  • callback: a function with the side effect logic.

  • dependencyArray: optional, determines when to re-run the effect.


✅ Common useEffect Use Cases


✅ 1. Run on Every Render

useEffect(() => {
  console.log("Component rendered or re-rendered");
});

No dependency array → runs after every render.


✅ 2. Run Only Once on Mount

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

Empty dependency array [] → runs only once after initial render.


✅ 3. Run When a State Changes

useEffect(() => {
  console.log(`Emotion changed to: ${emotion}`);
}, [emotion]);

The effect will re-run only when the emotion value changes.


๐Ÿ“˜ Full Example

App.js

import { useState, useEffect } from 'react';

function App() {
  const [emotion, setEmotion] = useState("happy");

  useEffect(() => {
    console.log(`It's ${emotion} right now`);
  }, [emotion]);

  return (
    <div className="App">
      <h1>Current emotion is {emotion}</h1>
      <button onClick={() => setEmotion("sad")}>Sad</button>
      <button onClick={() => setEmotion("excited")}>Excited</button>
    </div>
  );
}

๐Ÿ” Explanation

  • useEffect is called after the DOM is updated.

  • Every time emotion changes, useEffect logs the new value.

  • React watches [emotion] in the dependency array and only triggers the effect when it changes.


๐Ÿงช Experiment:

Try modifying the useEffect to simulate other side effects like a timer:

useEffect(() => {
  const timer = setTimeout(() => {
    console.log("3 seconds passed!");
  }, 3000);

  return () => clearTimeout(timer); // Cleanup
}, [emotion]);

๐Ÿงผ Cleanup in useEffect

If your effect returns a function, React will run that as a cleanup function before the component is removed or before re-running the effect.


It is possible to implement side effects in your components with the useEffect Hook.

Timer functions, direct DOM updates, and data fetching are a few instances of side effects.

It takes two arguments to useEffect. It is optional to provide the second argument.

useEffect(<function>, <dependency>) 

UseEffect is a significant hook included in the React library. Furthermore, because it's usually used to control side effects unrelated to a component's render, this one can feel a little bit complicated. UseEffect is frequently useful for tasks like working with animations, loading data, and sending terminal messages. Now let's examine useEffect fundamentally using a console log. Therefore, the first thing we want to do is import useEffect from React, and then we're going to use this useEffect hook inside our app component. This time, we're going to pass in a function to this instead of setting this equal to an array of some kind.

The first is this function, which we will call each time we desire our effect to occur. The second, however, concerns the timing of the effect's actual call. We are going to introduce an empty array into this. 

 An empty array indicates that the effect will not be invoked again following the initial render. It will therefore only be called once upon component rendering, not when we modify this emotion. Because we can use it to specify when this should be called, we have named this array the dependence array. Should it just be called once when our component renders? An alternative would be to send in a property, like as a state value, and have it watch this array for changes. Check this out, then.

We will see this useEffect fire whenever this emotion changes. 

—----------------npm start

App.js

import { useState, useEffect } from 'react';

function App() {

  const [emotion, setEmotion] = useState("happy");

 

  useEffect(()=>{

    console.log(`It's ${emotion} right now`);

  }, [emotion]);




Comments

Popular posts from this blog

React Full Stack Project Design Build Launch

React useState Hook – Complete Guide

Building an AI-Powered App with Next.js, Tailwind CSS, and OpenAI API