Mastering React Hooks as a beginner - useEffect()

As a beginner, you might find them a bit tricky, especially when you're trying to understand the underlying principles. But don’t worry! We're going to decode each hook in an easy-to-understand way, with fun examples so you’ll never forget them. Let’s dive into the magic of hooks! useEffect() – Side Effects? What Are They? You’ve probably heard this one a lot: “useEffect is used to handle side effects.” But what does that even mean? What are side effects? It’s kind of like asking, “What’s for dinner?” and someone replying, “Food.” Sure, but what kind of food? Let’s break it down. What are Side Effects? In React, side effects are any actions that happen outside of the normal React rendering process. These are things that can affect the outside world, like: Fetching data from an API Updating the DOM directly Subscribing to a service (like WebSocket or events) Setting up timers (setTimeout, setInterval) So basically, side effects are things your code does that React doesn’t directly manage, but which affect the UI or other parts of the app. useEffect(() => { // Here is where the magic happens }, [dependencies]) The useEffect hook accepts two parameters: A function that contains your side effect logic. A dependencies array that tells React when the effect should run. Example: Fetching Data Imagine you’re building a dashboard, and you need to fetch data from a server when the component mounts. Here’s how you can do that using useEffect. import React, { useState, useEffect } from 'react'; function Dashboard() { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/dashboard-data') .then(response => response.json()) .then(data => setData(data)); }, []); // The empty array means this effect runs only once (like componentDidMount) return data ? {JSON.stringify(data)} : Loading...; } export default Dashboard; Dependencies: The Secret Sauce The second argument, the dependencies array, controls when the effect should re-run. If you want it to run only once when the component mounts, you pass an empty array ([]), as shown above. If you want it to run whenever a certain variable changes, you can pass that variable inside the array. Example: Updating on Data Change useEffect(() => { console.log("Data has changed:", data); }, [data]); // Runs every time `data` changes The Cleanup Function – The Cleanup Crew But wait! There's more. What if your component is removed from the UI and you need to clean up some resources, like cancelling a network request or clearing a timer? That’s where the cleanup function comes in. The cleanup function runs when your component is about to be removed from the DOM or when the effect is about to run again (i.e., when a dependency changes). useEffect(() => { const timer = setInterval(() => { console.log("Timer is ticking..."); }, 1000); // Cleanup: This will clear the timer when the component unmounts return () => { clearInterval(timer); }; }, []); // Empty dependency array means this effect only runs once

Apr 8, 2025 - 06:24
 0
Mastering React Hooks as a beginner - useEffect()

As a beginner, you might find them a bit tricky, especially when you're trying to understand the underlying principles. But don’t worry! We're going to decode each hook in an easy-to-understand way, with fun examples so you’ll never forget them. Let’s dive into the magic of hooks!

useEffect() – Side Effects? What Are They?

You’ve probably heard this one a lot: “useEffect is used to handle side effects.” But what does that even mean? What are side effects? It’s kind of like asking, “What’s for dinner?” and someone replying, “Food.” Sure, but what kind of food? Let’s break it down.

What are Side Effects?

In React, side effects are any actions that happen outside of the normal React rendering process. These are things that can affect the outside world, like:

  • Fetching data from an API
  • Updating the DOM directly
  • Subscribing to a service (like WebSocket or events)
  • Setting up timers (setTimeout, setInterval)

So basically, side effects are things your code does that React doesn’t directly manage, but which affect the UI or other parts of the app.

useEffect(() => {
  // Here is where the magic happens
}, [dependencies])

The useEffect hook accepts two parameters:

  • A function that contains your side effect logic.
  • A dependencies array that tells React when the effect should run.

Example: Fetching Data

Imagine you’re building a dashboard, and you need to fetch data from a server when the component mounts. Here’s how you can do that using useEffect.

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

function Dashboard() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/dashboard-data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);  // The empty array means this effect runs only once (like componentDidMount)

  return data ? <div>{JSON.stringify(data)}</div> : 

Loading...p>; } export default Dashboard;

Dependencies: The Secret Sauce

The second argument, the dependencies array, controls when the effect should re-run. If you want it to run only once when the component mounts, you pass an empty array ([]), as shown above. If you want it to run whenever a certain variable changes, you can pass that variable inside the array.

Example: Updating on Data Change

useEffect(() => {
  console.log("Data has changed:", data);
}, [data]);  // Runs every time `data` changes

The Cleanup Function – The Cleanup Crew

But wait! There's more. What if your component is removed from the UI and you need to clean up some resources, like cancelling a network request or clearing a timer? That’s where the cleanup function comes in.

The cleanup function runs when your component is about to be removed from the DOM or when the effect is about to run again (i.e., when a dependency changes).

useEffect(() => {
  const timer = setInterval(() => {
    console.log("Timer is ticking...");
  }, 1000);

  // Cleanup: This will clear the timer when the component unmounts
  return () => {
    clearInterval(timer);
  };
}, []); // Empty dependency array means this effect only runs once