Skip to content

Instantly share code, notes, and snippets.

@tech-chieftain
Created June 10, 2024 08:31
Show Gist options
  • Save tech-chieftain/df49b378309b006d125dc3a686dc9274 to your computer and use it in GitHub Desktop.
Save tech-chieftain/df49b378309b006d125dc3a686dc9274 to your computer and use it in GitHub Desktop.

React useEffect Discussion

The goal from this discussion is to solidify your understanding about useEffect after studying about it before the class and in the class.

Please discuss the following questions between you and answer them in the comment section below.

Questions:

  1. What is useEffect?
  2. What do we mean when we say that useEffect is a hook?
  3. useEffect gets executed in 3 different ways, what are they? (Adding code examples would be beneficial)
@Letagoeve
Copy link

Letagoeve commented Jun 10, 2024

Members:
-@Yenkosii
-@Geraldmutsw
-@Letagoeve

1.useEffect is a React hook that allows you to handle side effects in function components. These side effects can involve tasks such as data fetching, setting up subscriptions, or manipulating the DOM directly. By leveraging useEffect, you can make sure your components interact with external systems (like APIs or the DOM) appropriately and efficiently

2.When we say that useEffect is a hook in React, we mean that it's a special function provided by React that allows us to perform side effects in function components

  1. -Subsequent Renders based on Dependencies: You can control when useEffect re-runs using a dependency array as the second argument. This array lists the values or variables that the effect relies on. If any of these dependencies change, useEffect will run again after the component re-renders.
    CODE FOR SUBSEQUENT RENDERING

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

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

useEffect(() => {
const fetchData = async () => {
const response = await fetch('https://api.example.com/data');
const fetchedData = await response.json();
setData(fetchedData);
};

fetchData();

}, []); // Empty dependency array for now (replace with relevant dependencies)

return (


{data ? (

Fetched Data: {data.message}


) : (

Loading data...


)}

);
}

export default FetchData;

-Initial Render/Mounting: When a component with useEffect is first displayed on the screen, the code inside the useEffect block runs after this initial render. This behavior is similar to the componentDidMount lifecycle method in class-based React components.

The useEffect hook in
CODE FOR "INITIAL RENDER/MOUNTING
import React, { useState, useEffect } from 'react';

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

useEffect(() => {
console.log('Component mounted!');
}, []); // Empty dependency array - runs only once after initial render

return (


You clicked {count} times
<button onClick={() => setCount(count + 1)}>Click me

);
}

export default MyComponent;

-Cleanup: The useEffect hook can optionally return a cleanup function. This function runs before the component unmounts (disappears from the screen) or before useEffect itself runs again due to a dependency change. This is useful for cleaning up things like subscriptions or timers to avoid memory leaks or unintended side effects.

CODE FOR CLEAN
import React, { useEffect } from 'react';

function MySubscription() {
useEffect(() => {
const subscription = someEvent.subscribe(() => {
console.log('Event happened!');
});

return () => {
  subscription.unsubscribe(); // Cleanup function to unsubscribe on unmount
};

}, []); // Empty dependency array (adjust if needed)

return (


Subscribed to an event!

);
}

export default MySubscription;

@MissAngelaKing
Copy link

Angela King
Lindokuhle Skosana
Koketso Lepulana

  1. useEffect is a hook that allows one to perform "side effects" in your components, some examples are to exchange data, directly updating the DOM, timers. useEffect accepts two arguments and the second one is optional.
  2. In react, the hook is a special function that lets you 'hook' into react features. Hooks allows us to useState and other react features without writing a class component.
  3. Firstly, after every render, if a dependency array, effect will run after every render .e.g
    useEffect(() => { console.log('Component rendered!'); // This will log on every render });

Secondly, once on mount and unmount, effect will only run after initial render (on mount) and the cleanup on unmount,
e.g useEffect(() => { console.log('Name changed to:', name); }, [])

Thirdly, when dependencies change, when providing dependencies array with specific variables . effect will run after initial render and whenever the dependencies change.
e.g useEffect(() => { console.log('Name changed to:', name); }, [name])

@ImisebenziEmihle
Copy link

ImisebenziEmihle commented Jun 10, 2024

Room 8 (Emihle & Nonhlanhla

  1. useEffect is a function provided by the React library, used for handling side effects in functional components. It's a way to run some code after the component has rendered, or when certain dependencies change. Side effects can include things like data fetching, subscriptions, or manually changing the DOM.

  2. When we say that useEffect is a hook, we mean that it's a special function that allows us to "hook into" the lifecycle of a component and execute some code at specific points.useEffect is one such hook, designed to seamlessly integrate with the React rendering process.

    1. We can have the useEffect hook without the array, the effect runs after every render and re-render of the component. eg.
      useEffect(() => {
      return () => {
      console.log('Component mounted!');
      });
  3. 2 We can have the useEffect hook with an empty array, where it will only run once at the beginning, at first render only. e.g
    useEffect(() => {
    return () => {
    console.log('Component unmounted!');
    };
    }, []);

2.3 If the useEffect has a non-empty array as argument, the hook will run at the start and every time a change is made to the array. e.g
useEffect(() => {
console.log('Count changed to:', count);
}, [count]); (Dependency array includes count, so it runs when count changes)

@Tumelo2748
Copy link

  1. Selepe Thinane

  2. Mthokozisi Dlamini

  3. lethukuthula Mkhondo

  4. useEffect is react hook that can be used perform side effects

  5. is a hook because it's a special function you can "hook" into your React components

  • It allows you to perform actions outside the normal rendering process of a component, like fetching data or setting timers. This keeps your component code cleaner and easier to understand.

useEffect can be executed on every render / at the beginning and when changes occur

const MyComponent = () => {
const [data, setData] = useState(null); // Assume useState for data

useEffect(() => {
console.log('This runs after every render');
});

useEffect(() => {
// Fetch data on initial render (empty dependency array)
fetchData().then(data => setData(data));
}, []);

useEffect(() => {
// Do something whenever data changes (dependency on data)
if (data) {
console.log("Data received:", data);
}
}, [data]);

return (


{data &&

Fetched data: {data}

}

);
};

@PhamelaMhlaba
Copy link

Team Members(Phamela, Siyabonga and Nhlanhla)
Answers.
0. useEffect` is a hook in React that allows you to perform side effects in function components. It's used to execute code that needs to run after the component renders, such as data fetching, subscriptions, or manually changing the DOM.

  1. React's useEffect hook, a special function for functional components, manages side effects (fetching data, timers) by running a function after the component renders, keeping your rendering logic clean and side effects well-controlled.

2- useEffect execution depends on the dependency array you provide:

On Every Render: Leave the dependency array empty ([]):

JavaScript
useEffect(() => {
// Code to run on every render
}, []);

  • On Mount Only: Pass an empty dependency array:

JavaScript
useEffect(() => {
// Code to run only on initial render (similar to componentDidMount)
}, []);

  • On Mount and When Dependencies Change: List the state or prop values the effect relies on:

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

useEffect(() => {
// Code to run on mount and whenever count changes
}, [count]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment