React useEffect Hooks

React useEffect Hooks

In React, the useEffect hook lets you run side effects in your functional components. Side effects can include data fetching, subscriptions, or manually changing the DOM.

useEffect(() => {
  // Side effect code here
}, [dependencies]);        

Key Points:

  1. Side Effect Code: The function inside useEffect runs after the component renders. You can use it for tasks like fetching data, setting up subscriptions, or updating the document title.
  2. Dependencies Array: The second argument is an array of dependencies. If any of the values in the array change, the effect runs again.
  3. If you pass an empty array [], the effect runs only once (on mount).
  4. If you omit the array, the effect runs after every render.
  5. Cleanup Function: Optionally, you can return a function inside useEffect to clean up resources (e.g., unsubscribing from a service) when the component unmounts or before the next effect is run.

useEffect(() => {
  const timer = setTimeout(() => {
    console.log('Timer triggered');
  }, 1000);
  
  return () => clearTimeout(timer); // Cleanup when the component unmounts
}, []);        

Example:

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

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;

    // Cleanup: Optional return function (for example, to clear an interval)
    return () => {
      console.log('Cleanup on component unmount or effect re-run');
    };
  }, [count]); // Only re-run the effect if count changes

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default ExampleComponent;        

In this example, the document title updates every time the count value changes.

Example 1: Fetching Data on Component Mount

import { useEffect, useState } from 'react';

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

  useEffect(() => {
    // Fetch data when the component mounts
    fetch('https://api.example.com/data')
      .then((response) => response.json())
      .then((data) => setData(data));
  }, []); // Empty array ensures this effect runs only once

  return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
}        
Ahmad Hussein

Operations Manager .Hospitals Management

5 个月

Very useful

回复
Arif Sharief

Social Media Manager I Influencer I Free Lancer I Personal Branding I Brand Management I LinkedIn Growth #contentcreator #Affiliatemarketing #Facebookbusinessmanager #Digitalmarketingspecialist

5 个月

Interesting

回复
Arti Yadav

Elevating Careers ??| Open for promotion| Excel Expert?? |Helping brands to grow ??

5 个月

Great advice

Rizwiya Kausar Khan

Optimizing LinkedIn Profiles to Attract More Clients & Career Opportunities | Get Your "FREE LinkedIn Profile Audit" Click ???? | Helped 60+ Professionals | Linkedin Personal Branding

5 个月

helpful

回复

要查看或添加评论,请登录

Pushpendra Tripathi的更多文章

  • useState() Hook in React

    useState() Hook in React

    The useState() Hook in React is used to add state to functional components. It allows you to declare state variables in…

    15 条评论

社区洞察

其他会员也浏览了