Side Effects & Lifecyle | Hands on React (2024)

Side Effects (in function components)

Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects. Whether or not you’re used to calling these operations “side effects” (or just “effects”), you’ve likely performed them in your components before.

useEffect

This Hook should be used for any side-effects you’re executing in your render cycle.

What does useEffect do?

By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we'll refer to it as our “effect”), and call it later after performing the DOM updates.

Using useEffect

useEffect() takes a function as an input and returns nothing.

The function it takes will be executed for you:

  • after the render cycle
  • after every render cycle
Lifecycle MethodsHookRenders
componentDidMountuseEffect(()=>{ ... }, [ ])after first render only
componentDidUpdateuseEffect(()=>{... }, [dependency1, dependency2])after first render AND subsequent renders caused by a change in a dependency
componentWillUnmountuseEffect(() => { ... return ()=> {...cleanup}})
shouldComponentUpdateno comparable hook, instead, wrap function component in React.memo(List)renders only if a prop changes
componentWillMountdeprecated so no comparable hook
componentWillUpdatedeprecated so no comparable hook

Example (after first render only)

Here is the the common use case example we saw in the state section. It has been updated to loadData after the initial rendering of the component.

const { useState, useEffect } = React;

function App() {
const [loading, setLoading] = useState(false);
const [data, setData] = useState(null);
function loadData() {
setLoading(true);
setTimeout(() => {
setLoading(false);
setData([1, 2, 3, 4, 5]);
}, 1000);
}

useEffect(loadData, []);

return (
<>
{loading && <p>Loading...</p>}
{data && <pre>{JSON.stringify(data, null, 1)}</pre>}
</>
);
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);

Example (after first render AND subsequent renders caused by a change in a dependency)

Here is the the common use case example we saw in the state section. It has been updated to loadData after the initial rendering of the component.

const { useState, useEffect } = React;

function App() {
const [loading, setLoading] = useState(false);
const [data, setData] = useState(null);
const [page, setPage] = useState(1);
function loadData() {
setLoading(true);
setTimeout(() => {
setLoading(false);
if (page === 1) {
setData([1, 2, 3, 4, 5]);
} else if (page === 2) {
setData([6, 7, 8, 9, 10]);
} else {
setData(null);
}
}, 1000);
}

useEffect(loadData, [page]);

function handleNext() {
setPage((currentPage) => currentPage + 1);
}

return (
<>
{loading && <p>Loading...</p>}
{data && <pre>{JSON.stringify(data, null, 1)}</pre>}
<span>Current Page: {page}</span>
<button onClick={handleNext}>Next</button>
</>
);
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);

useEffect Cleanup Example

function Clock() {
const [time, setTime] = React.useState(new Date().toLocaleTimeString());

React.useEffect(() => {
const timerID = setInterval(refresh, 1000);
return () => {
clearInterval(timerID);
};
}, []);

const refresh = () => {
setTime(new Date().toLocaleTimeString());
};

return (
<div>
<p>{time}</p>
</div>
);
}

ReactDOM.createRoot(document.getElementById('root')).render(<Clock />);

Lifecycle (in class components)

What are Lifecycle Methods

Lifecycle methods are custom functionality that gets executed during the different phases of a component. There are methods available when the component gets created and inserted into the DOM (mounting), when the component updates, and when the component gets unmounted or removed from the DOM.

Understanding Mounting

The main job of React is to figure out how to modify the DOM to match what the components want to be rendered on the screen.

React does so by "mounting" (adding nodes to the DOM), "unmounting" (removing them from the DOM), and "updating" (making changes to nodes already in the DOM).

This process of creating instances and DOM nodes corresponding to React components, and inserting them into the DOM, is called mounting.

React Lifecycle Methods Diagram: Common Methods

Here is an interactive version that links to the documentation for each method: React Lifecycle Methods Diagram

Using LifeCycle Methods

In applications with many components, it’s very important to free up resources taken by the components when they are destroyed.

We want to set up a timer whenever the Clock is rendered to the DOM for the first time. This is called “mounting” in React.

We also want to clear that timer whenever the DOM produced by the Clock is removed. This is called “unmounting” in React.

We can declare special methods on the component class to run some code - when a component mounts : - set up a timer to refresh the clock every second - when a component unmounts: - tear down the timer when the component is removed to prevent a memory leak

class Clock extends React.Component {
state = {
time: new Date().toLocaleTimeString(),
};

refresh = () => {
this.setState({ time: new Date().toLocaleTimeString() });
};

render() {
return (
<div>
<p>{this.state.time}</p>
</div>
);
}

componentDidMount() {
this.timerID = setInterval(this.refresh, 1000);
}

componentWillUnmount() {
clearInterval(this.timerID);
}
}

ReactDOM.createRoot(document.getElementById('root')).render(<Clock />);

Reference

Side Effects & Lifecyle | Hands on React (2024)
Top Articles
Real Estate Crowdfunding Returns
Follow Your Passion Really Is Good Advice: 3 Ways To Fuel Your Career
Great Clips Mount Airy Nc
Shs Games 1V1 Lol
2021 Tesla Model 3 Standard Range Pl electric for sale - Portland, OR - craigslist
Day Octopus | Hawaii Marine Life
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Whitley County Ky Mugshots Busted
What to do if your rotary tiller won't start – Oleomac
Everything You Need to Know About Holly by Stephen King
What Time Chase Close Saturday
Missed Connections Dayton Ohio
Icommerce Agent
Uktulut Pier Ritual Site
Pekin Soccer Tournament
St Maries Idaho Craigslist
Farmer's Almanac 2 Month Free Forecast
Mychart Anmed Health Login
Unforeseen Drama: The Tower of Terror’s Mysterious Closure at Walt Disney World
Allentown Craigslist Heavy Equipment
18889183540
Wbiw Weather Watchers
Self-Service ATMs: Accessibility, Limits, & Features
Wemod Vampire Survivors
Seeking Arrangements Boston
A Man Called Otto Showtimes Near Cinemark University Mall
Yugen Manga Jinx Cap 19
California Online Traffic School
Kirsten Hatfield Crime Junkie
Hefkervelt Blog
§ 855 BGB - Besitzdiener - Gesetze
Stickley Furniture
Kuttymovies. Com
Southtown 101 Menu
Elanco Rebates.com 2022
Vlocity Clm
Little Caesars Saul Kleinfeld
Mumu Player Pokemon Go
Free Robux Without Downloading Apps
Mistress Elizabeth Nyc
Ticketmaster Lion King Chicago
Shih Tzu dogs for sale in Ireland
Dynavax Technologies Corp (DVAX)
Gun Mayhem Watchdocumentaries
Sas Majors
Giovanna Ewbank Nua
Frontier Internet Outage Davenport Fl
Dicks Mear Me
Enjoy Piggie Pie Crossword Clue
1Tamilmv.kids
2000 Fortnite Symbols
Latest Posts
Article information

Author: Golda Nolan II

Last Updated:

Views: 5752

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Golda Nolan II

Birthday: 1998-05-14

Address: Suite 369 9754 Roberts Pines, West Benitaburgh, NM 69180-7958

Phone: +522993866487

Job: Sales Executive

Hobby: Worldbuilding, Shopping, Quilting, Cooking, Homebrewing, Leather crafting, Pet

Introduction: My name is Golda Nolan II, I am a thoughtful, clever, cute, jolly, brave, powerful, splendid person who loves writing and wants to share my knowledge and understanding with you.