React Call Component Again After Mounting
Editor's notation: This mail service was last updated on xxx July 2021. Information technology may yet contain information that is out of appointment.
States in React, like props, are objects that store data and affect how a component renders or behaves. Unlike props, states are managed completely within the component and can be changed over time.
User actions, network activity, API requests, or specific application behaviors tin often trigger changes in state for React components.
In this commodity, nosotros'll review:
- What is a component land in React?
- How practice I access a component state in React?
- How practise I update my component state in React?
- How do I use
setState()
in React? - Using
setState()
in React lifecycle methods
What is a component country in React?
Components that have a state are referred to equally stateful components, while those that do not have states are stateless components.
A component can have an initial state set, access it, and update it. In the lawmaking block below, nosotros are setting the component'south initial state. This is washed through the constructor method:
import React, { Component } from 'react'; class Food extends Component { constructor(props) { super(props) this.land = { fruits: ['apple', 'orange'], count: 0 } } }
Because states are patently JavaScript objects, this.state
must be equal to an object:
this.state = { fruits: ['apple', 'orange'], count: 0 }
Avert confusing the state
object with other case properties. It's easy to assume you lot can ascertain some other object in the constructor and endeavour to apply it like land
, but the state
instance is a special ane considering React manages it:
... //constructor function above this.country = { fruits: ['apple tree', 'orangish'], count: 0 } this.user = { name: 'Obaseki Nosa' } ...
Although both this.country
and this.user
are objects initialized in the constructor, merely this.state
reacts with setState()
and is managed by React.
How exercise I admission a component state in React?
We tin can access component states like other object using this.state.property_name
.
To access the count
in the above case, we;ll apply this.state.count
:
return() { render ( <div className = "container"> <h2> Howdy!!!</h2> <p> I have {this.state.count} fruit(s)</p> </div> ); }
How practice I update my component state in React?
Although it is technically possible to write to this.state
from anywhere in your lawmaking, it does not prompt a rerender, which would lead to unstable and incorrect state values when trying to access values through this.country
.
The simply place y'all should directly write to this.state
is the component's constructor method.
Utilise the setState()
method everywhere else; doing and so accepts an object that eventually merges into the component's existing country.
For example, the following does not rerender a component:
// Wrong this.land.name = 'Obaseki Nosa';
Instead, use setState()
.
How do I utilise setState()
in React?
The setState()
schedule changes to the component's state object and tells React that the component and its children must rerender with the updated country:
// Right this.setState({name: 'Obaseki Nosa'});
React intentionally waits until all components telephone call setState()
in their outcome handlers before rerendering. This boosts performance by fugitive unnecessary rerenders.
setState()
can be considered as a request instead of an immediate control to update the component. This is why trying to use this.state
immediately after a setState()
leads to incorrect behaviors:
// Trying to change the value of this.state.count from previous example this.setState({ count: 4 }); panel.log(this.state.count); // 0
this.state.count
returns 0
because even though the value is gear up with setState()
, information technology was only scheduled and not rerendered before attempting to utilise the value with this.state
.
setState()
always leads to a rerender unless shouldComponentUpdate()
returns fake
.
Using setState()
in React lifecycle methods
Calling setState()
in React'south lifecycle methods requires a certain level of caution. There are a few methods where calling setState()
leads to undesirable results and others to avert completely. Let'south look at a few methods and how they react when calling setState()
render()
Calling setState()
here makes it possible for a component to produce space loops.
The render()
function should be pure, significant that it does not modify a component's country. It returns the same result each fourth dimension it's invoked, and it does not directly interact with the browser.
In this case, avert using setState()
here.
constructor()
Exercise non call setState()
in constructor()
. Instead, if a component needs to utilize a local state, assign the initial state to this.land
directly in the constructor.
componentDidMount()
componentDidMount()
invokes immediately subsequently a component mounts. You can call setState()
immediately in componentDidMount()
and triggers an extra rendering, but this happens earlier the browser updates the screen, calling return()
twice.
componentDidUpdate()
componentDidUpdate()
invokes immediately subsequently updating. You tin can call setState()
immediately here, but it must be wrapped in a condition similar in the example below, or it causes an infinite loop:
componentDidUpdate(prevProps, prevState) { let newName = 'Obaseki Nosa' // Don't forget to compare states if (prevState && prevState.name !== newName) { this.setState({name: newName}); } }
componentWillUnmount()
Exercise non call setState()
here because the component does not rerender. Once a component instance unmounts, information technology never mounts once more.
Conclusion
This concludes our overview of setState()
. Some things to remember when using setState()
include:
-
setState()
is async, significant there is no guarantee that the land has updated when trying to admission the value immediately - You can only alter
land
withsetState
and React will react to the change
Cheers!!!
Full visibility into production React apps
Debugging React applications can be difficult, particularly when users experience issues that are hard to reproduce. If yous're interested in monitoring and tracking Redux land, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you lot can amass and report on what land your application was in when an issue occurred. LogRocket also monitors your app'due south performance, reporting with metrics similar client CPU load, customer memory usage, and more.
The LogRocket Redux middleware bundle adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.
Modernize how you debug your React apps — start monitoring for free.
Source: https://blog.logrocket.com/using-setstate-react-components/
0 Response to "React Call Component Again After Mounting"
Post a Comment