State and Lifecycle - React (2023)

These documents are old and will not be updated. Go toreaguj.devfor new React documents.

These new documentation pages teach modern React and include live examples:

This page introduces the concept of states and lifecycles in a React component. here you canmore detailed information about the API for componentsmeet.

Let's look at an example of a program clockprevious sectionAbout. no chapterrendering elements, we learned only one way to update the UI. We callroot.render()to change the rendered output:

untilsource=ReactDOM.criarRoot(document.getElementById('source')); function marking() { untilelement= ( <dz> <h1>Hello World!h1> <h2>That's it{novo Data().doLocaleTimeString()}.h2> dz> );source.rendering(element);}set range(marking, 1000);

Experience not CodePen

In this section, we'll learn how to do that.ClockMake the component truly reusable and independent. Set your own timer and update every second.

We can start by describing what the watch looks like:

untilsource=ReactDOM.criarRoot(document.getElementById('source'));function Clock(props) { turn back ( <dz> <h1>Hello World!h1> <h2>That's it{}.h2> dz> );}function marking() {source.rendering(<Clock data={novo Data()} />);}set range(marking, 1000);

Experience not CodePen

However, a fundamental requirement is missing: the fact thatClockcreating a timer and updating the UI every second should be an implementation detailClockTo be.

Ideally, we'd like to write it just once andClocklet the update run by itself:

source.rendering(<Clock />);

To implement it, we needClockAdd "Status" to the component.

State is similar to props but is private and fully controlled by the component.

We already havepreviously mentionedthat components defined as classes have some additional characteristics. Local State is just that: a resource only available in class.

(Video) React State & Lifecycle Explained (Class/Hooks) - MicroBytes (2020)

Casting from a function to a class

component likeClockyou can convert to a class in five steps:

  1. create aclasse ES6with the same name, that isReact.Componentexpanded.
  2. Create an empty method calledrender().
  3. Move function content torender()Method.
  4. to replacepropszit.propscrender()Method.
  5. Remove any remaining empty function declarations.
classroom Clock stretches to react.Hey { rendering() { turn back ( <dz> <h1>Hello World!h1> <h2>That's it{}.h2> dz> ); }}

Experience not CodePen

Clockit is now defined as a class, not a function.

To dierenderingthe method is called every time there is an update, but as long asrender on same DOM node, just one instanceClockused class. This allows us to use additional features such as local state and lifecycle methods.

Add a local state to the class

we postponeddatafrom props to condition in three steps:

  1. to replaceta.rekwizyty.datazdez.stan.datacrender()Method:
classroom Clock stretches to react.Hey { rendering() { turn back ( <dz> <h1>Hello World!h1> <h2>That's it{}.h2> dz> ); }}
  1. add adesigner classadded to initialThis statusattributes:
classroom Clock stretches to react.Hey { constructor(props) { Super(props); {data: novo Data()}; } rendering() { turn back ( <dz> <h1>Hello World!h1> <h2>That's it{}.h2> dz> ); }}

notice how wepropspassed to the base constructor:

 constructor(props) { Super(props); {data: novo Data()}; }

Class components must always include a base constructorpropsto call.

  1. remove itdataProp vomElement:
source.rendering(<Clock />);

Later, we'll paste the timer code back into the component.

The result looks like this:

classroom Clock stretches to react.Hey { constructor(props) { Super(props); {data: novo Data()}; } rendering() { turn back ( <dz> <h1>Hello World!h1> <h2>That's it{}.h2> dz> ); }}untilsource=ReactDOM.criarRoot(document.getElementById('source'));source.rendering(<Clock />);

Experience not CodePen

So let's be sureClocksets your own timer and updates every second.

(Video) ReactJS Tutorial - 22 - Component Lifecycle Methods

Add Lifecycle Methods to the Class

In applications with many components, it is important to free up resources when a component is removed.

we want onecreate timers, SeClockis rendered to the DOM for the first time. This is called "assembly" in React.

we also wanttimers removedit will be if it is zClockthe created DOM element is removed. In React, this is called "disassembly".

We can declare special methods in a component class to execute specific code when assembling and disassembling:

classroom Clock stretches to react.Hey { constructor(props) { Super(props); {data: novo Data()}; } componenteDidMount() { } component will be disassembled() { } rendering() { turn back ( <dz> <h1>Hello World!h1> <h2>That's it{}.h2> dz> ); }}

These methods are called "lifecycle methods".

To dieDidMount() componentThe method runs after the components have been rendered into the DOM. This is a good place to put the timer:

 componenteDidMount() { Dez.timer id= set range( () => Dez.marking(), 1000 ); }

Notice how we put the timer IDDez(ten.identifier timera) save to your computer.

One secondit.propsconfigured by React i itselfThis statushas a special meaning, you can manually add additional fields to the class if you want to store something that doesn't participate in the data stream (timer ID for example).

We will use a timer incomponenteWillDesmontar()Cancel lifecycle method:

 component will be disassembled() { clear range(Dez.timer id); }

Finally, we'll add a method calledmarkingimplement itClockit will ring every second.

she goesthis.setState()use to schedule component local state update:

classroom Clock stretches to react.Hey { constructor(props) { Super(props); {data: novo Data()}; } componenteDidMount() { Dez.timer id= set range( () => Dez.marking(), 1000 ); } component will be disassembled() { clear range(Dez.timer id); } marking() { Dez.define state({ data: novo Data() }); } rendering() { turn back ( <dz> <h1>Hello World!h1> <h2>That's it{}.h2> dz> ); }}untilsource=ReactDOM.criarRoot(document.getElementById('source'));source.rendering(<Clock />);

Experience not CodePen

Now the clock is ticking every second.

(Video) React Component Lifecycle - Hooks / Methods Explained

Let's quickly summarize what's going on here and the order in which the methods are called:

  1. Sesomeroot.render()is provided, React calls the constructorClockitem up. ThereClockneeds to display the current time, initialize itThis statuswith an object containing the current time. We will update this status later.
  2. react then callrender()methodClockitem up. This is how React knows what to show on the screen. React then updates the DOM according to the rendered outputClock.
  3. if you leaveClockinserted into the DOM, React calls LifecycleDidMount() componentABOUT. Including calls toClockcomponent to create a browser on a timer that every secondmarking()method calls.
  4. Every second the browser calls a methodmarking()linked method. As part of these plansClocka component that updates the user interface where thissetState()connection to the object containing the current time. thanks tosetState()-call, React knows the state has changed and calls itrender()methods of relearning what should be displayed on the screen. this time willdez.stan.datacrender()the method must be different and the rendered content contains the updated time. React updates the DOM accordingly.
  5. SeClockcomponent is always removed from the DOM, React calls the methodcomponenteWillDesmontar()The lifecycle method and timer stop.

Use states correctly

There are three things you care aboutsetState()should know.

Do not edit state directly

This will not re-render the component, for example:

// 'Hey';

use insteadsetState():

// ValidDez.define state({comment: 'Hey'});

The only place where you areThis statusyou can define is the constructor.

Status updates can be asynchronous

For performance reasons, React may do somesetState()Combine conversations into one update.

EUit.propsEUThis statuscan be updated asynchronously, do not rely on the ability to use the values ​​for next-state calculations.

For example, this code cannot update the counter.

// MalDez.define state({ lada: Dez.props.increase,});

To avoid this, we use the second formsetState()which takes a function instead of an object. This function takes the previous state as the first argument and the props at the time of the update as the second argument:

// ValidDez.define state((country,props) => ({ lada:country.lada+props.increase}));

we have one upstairslambda functionused, but the normal functions also work:

// ValidDez.define state(function(country,props) { turn back { lada:country.lada+props.increase};});

Status updates are merged

if yousetState()calls, React will bind the given object to the current state.

For example, your state can contain several independent variables:

(Video) State and Lifecycle of Component in React in Hindi 2021 | React.js setstate method

 constructor(props) { Super(props); { posts: [], comments: [] }; }

So you can use them independently in differentsetState()-Update connections.

 componenteDidMount() { downloading posts().Then(responder => { Dez.define state({ posts:responder.posts }); }); Download comments().Then(responder => { Dez.define state({ comments:responder.comments }); }); }

The connection is only superficial andthis.setState({comentar})sheetsthis.status.poststhey exist but have been replacedthis.state.comments.

Top-down data flow

Neither parent nor child components can know whether a given component is stateful or stateless, nor should they care whether it is defined as a function or a class.

Therefore, the state is often referred to as local or closed. It is only available to the component that owns and creates it. For any other ingredient.

A component can choose whether to pass its state as props:

<h2>That's it{}.h2>

This also works for custom components:

<formatted date data={} />

To dieformatted dateleverage ingredientdataas a prop and I don't know if it's from the state or propsClockcomes from or was entered manually:

function formatted date(props) { turn back <h2>That's it{}.h2>;}

Experience not CodePen

This is commonly referred to as "top-down" or "one-way" data flow. Each state always belongs to a specific component, and any data or UI derived from that state can only affect all "lower" components in the tree.

If you think of the component tree as a supporting cascade, each component state is like an additional source of water that flows from a random location and goes down with it.

To show that all elements are really independent, let's create aApplicationcomponent threerendering:

function Application() { turn back ( <dz> <Clock /> <Clock /> <Clock /> dz> );}
(Video) ReactJS - States & Lifecycle of Components (setState) | ReactJS Basics Made Easy

Experience not CodePen

AllClockcreates its own timer and updates automatically.

In React Apps, component implementation details that may change over time are considered stateless or stateful. You can use stateless components inside stateful components and vice versa.


1. React State Vs Props
(Web Dev Simplified)
2. Learn React #8: The React Lifecycle of a Functional Component
(Anthony Sistilli)
3. React Components as Living Things | State and Lifecycle Simplified
(deeecode - Simplify The Web)
4. React Tutorial #5 - State and Lifecycle
(Michael Kitas)
5. UseEffect React Hook Explained - React Lifecycle
6. React Component Lifecycle & Lifecycle methods | Complete React Course in Hindi #34
Top Articles
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated: 07/20/2023

Views: 5756

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.