-
Notifications
You must be signed in to change notification settings - Fork 0
28 Props and State
Understanding React 'setState' link
React components often have state. State can be anything, but think of things like whether a user is logged in or not and displaying the correct username based on which account is active. Or an array of blog posts. Or if a modal is open or not and which tab within it is active.
React components with state render UI based on that state. When the state componenet changes, so does the component UI.
setState() is the only legitimate way to update state after the initial state setup.
Example:
import React, { Component } from 'react';
class Search extends Component {
constructor(props) {
super(props);
state = {
searchTerm: '',
};
}
changeState(term) {
setState({ searchTerm: term });
}
}
/*
- Here, we're passing an object to `setState()`. The object contains the part of the state we want to update which, in this case, is the value of `searchTerm`.
- React takes this value and merges it into the object that needs it. It's sort of like the `Search` component asks what it should use for the value of `searchTerm` and `setState()` responds with an answer.
*/This is basically kicking off a process that React calls reconciliation.
-
The reconciliation process is the way React updates the DOM, by making changes to the component based on the change in state.
-
When the request to
setState()is triggered, React creates a new tree containing the reactive elements in the componenet (along with the updated state). This tree is used to figure out how theSearchcomponent's UI should change in response to the state changes by comparing it with the elements of the previous tree. React knows which changes to implement and will only update the parts of the DOM where necessary. This is why React is fast.
————— DO NOT DO THIS —————
Never mutate state directly. Always use setState() to change state. Modify state directly, like the snippet below will not cause the component to re-render.
————— DO NOT DO THIS —————
Example with a simple counter that increments and decrements on click.