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)
@thabiso-makolana
Copy link

thabiso-makolana commented Jun 10, 2024

Ntokozo
Thabiso
Mpilo

  1. is a Hook in React that allows you to perform side effects in your functional components. Side effects are operations that can affect something outside the scope of the function being executed, such as data fetching, and manually changing the DOM.
  2. we mean it is a special function provided by React that allows you to use state without writing a class component. Hooks, useEffect enables functional components to manage side effects and component lifecycle events in a way that was previously only possible in class components.
  3. 1. Running on Every Render
    If you do not provide a dependency array, the useEffect will run after every render of the component
useEffect(() => {
   console.log('Effect runs after every render');
   document.title = `You clicked ${count} times`;
 });

2. Running Once on Mount
If you provide an empty dependency array [], the useEffect will run only once after the initial render (similar to componentDidMount in class components).

useEffect(() => {
   console.log('Effect runs once after initial render');
   document.title = `You clicked ${count} times`;
 }, [])

3.Running on Dependency Change
If you provide a dependency array with specific variables, the useEffect will run after the initial render and whenever any of the dependencies change.

useEffect(() => {
    console.log('Effect runs after count changes');
    document.title = `You clicked ${count} times`;
  }, [count]); 

@hunny-bee
Copy link

Bonolo and Wesley

  1. It is a hook provided by React, it is used in functional components to perform side effects like fetching, subscriptions and changing the DOM
  2. It is a hook as it is provided by the React Hooks API and it also manages the component lifecycle in a declarative way
    • useEffect(() =>{
      fetchPost });
      The above code renders all the time

    • useEffect(() =>{
      fetchPost }, [ ]);
      The above code renders once

    • useEffect(() =>{
      fetchPost }) [ condition];
      The above code only renders when the condition in the square brackets is true

@PamelaGwala
Copy link

@sakhile Motha
@Vuyo Ngwane

1)useEffect is a React Hook that allows you to perform side effects in functional components. Side effects are operations that happen outside the regular rendering lifecycle of a React component
2)We mean that it's a special function that lets you perform side effects in your functional components, such as fetching data, directly interacting with the DOM, or setting up subscriptions. Hooks like useEffect enable functional components to use features that were previously only available in class components, making it easier to manage component logic and state.
3)No Dependency Array: useEffect runs after every render when you don't provide a dependency array.
useEffect(() => {
console.log();
});
*Empty Dependency Array: useEffect runs only once after the initial render when you provide an empty dependency array.

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

  • With Dependencies: useEffect runs after the initial render and whenever any of the dependencies change when you provide a dependency array with specific values.

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

@Mukoni-Nemauluma
Copy link

Mukoni-Nemauluma commented Jun 10, 2024

Members: Konanani, Samuel, Pumlani

  1. useEffect is a React hook that enables you to incorporate side effects, such as fetching data or modifying the DOM, within function components.
  2. When we say useEffect is a hook, we're referring to how it works with React's functional components. Hooks work like special tools that let functional components perform different task, like handling state. useEffect is one of these tools.

(a) After the initial render: This is the default behavior whenever you use useEffect without an empty dependency array.
import React, { useEffect } from 'react';

Example:

const MyComponent = () => {
useEffect(() => {
console.log('Effect executed after render');
});

return

Component Content
;
};

(b) On Mount Only:

import React, { useEffect } from 'react';

const MyComponent = () => {
useEffect(() => {
console.log('Effect executed on mount');
}, []);

return

Component Content
;
};
(c) When Dependencies Change:

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

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

useEffect(() => {
console.log('Effect executed when count changes:', count);
}, [count]);

return (


Count: {count}


<button onClick={() => setCount(count + 1)}>Increment

);
};

@Sharolinah-23
Copy link

Sharolinah-23 commented Jun 10, 2024

Sharon Matjila
Mpho Oganne
Hophney Lentsoana

1.useEffect is a hook that is used to handle the side effects such as fetching data and updating DOM.
2. We call useEffect a hook because it "hooks into" React's lifecycle features, enabling functional components to perform side effects and manage state, which were previously only possible in class components with lifecycle methods.
3. Initial render: Executes after the initial render of the component.
Example
function MyComponent() { useEffect(() => { console.log('Component rendered!'); // Runs after initial render }, []); // Empty dependency array ensures it runs only once on initial render return (

Hello World!
); }

Dependency change: Runs again if any dependency in the dependency array changes.
example//////
useEffect(() => {
console.log('Dependency changed!');
}, [dependency]);

Cleanup: Returns a function that runs before the component unmounts for cleanup tasks.
example/////
useEffect(() => {
const subscription = fetchData();
return () => subscription.unsubscribe(); // Cleanup function
}, []);

@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