score:145
With setState
the current and previous states are merged. With replaceState
, it throws out the current state, and replaces it with only what you provide. Usually setState
is used unless you really need to remove keys for some reason; but setting them to false/null is usually a more explicit tactic.
While it's possible it could change; replaceState currently uses the object passed as the state, i.e. replaceState(x)
, and once it's set this.state === x
. This is a little lighter than setState
, so it could be used as an optimization if thousands of components are setting their states frequently.
I asserted this with this test case.
If your current state is {a: 1}
, and you call this.setState({b: 2})
; when the state is applied, it will be {a: 1, b: 2}
. If you called this.replaceState({b: 2})
your state would be {b: 2}
.
Side note: State isn't set instantly, so don't do this.setState({b: 1}); console.log(this.state)
when testing.
score:2
Since replaceState
is now deprecated, here is a very simple workaround. Though it is probably quite seldom that you would / should resort to needing this.
To remove the state:
for (const old_key of Object.keys(this.state))
this.setState({ [old_key]: undefined });
Or, alternatively, if you don't want to have multiple calls to setState
const new_state = {};
for (const old_key of Object.keys(this.state))
new_state[old_key] = undefined;
this.setState(new_state);
Essentially, all previous keys in the state now return undefined
, which can very easily be filtered with an if
statement:
if (this.state.some_old_key) {
// work with key
} else {
// key is undefined (has been removed)
}
if ( ! this.state.some_old_key) {
// key is undefined (has been removed)
} else {
// work with key
}
In JSX:
render() {
return <div>
{ this.state.some_old_key ? "The state remains" : "The state is gone" }
</div>
}
Finally, to "replace" the state, simply combine the new state object with a copy of the old state that has been undefined
, and set it as state:
const new_state = {new_key1: "value1", new_key2: "value2"};
const state = this.state;
for (const old_key of Object.keys(state))
state[old_key] = undefined;
for (const new_key of Object.keys(new_state))
state[new_key] = new_state[new_key];
this.setState(state);
score:14
According to the docs, replaceState
might get deprecated:
This method is not available on ES6 class components that extend React.Component. It may be removed entirely in a future version of React.
score:49
Definition by example:
// let's say that this.state is {foo: 42}
this.setState({bar: 117})
// this.state is now {foo: 42, bar: 117}
this.setState({foo: 43})
// this.state is now {foo: 43, bar: 117}
this.replaceState({baz: "hello"})
// this.state. is now {baz: "hello"}
Take note of this from the docs, though:
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.
Same goes for replaceState()
Source: stackoverflow.com
Related Query
- Updating an object with setState in React
- Why does calling react setState method not mutate the state immediately?
- When to use React setState callback
- React setState not updating state
- React setState not Updating Immediately
- setState vs replaceState in React.js
- allow typescript compiler to call setState on only one react state property
- React setState + Where does 'prevState' come from?
- React warning about setState in unmounted component
- React - setState in componentWillReceiveProps
- React setState can only update a mounted or mounting component
- React setState hook from scroll event listener
- SetState of an array of Objects in React
- Right way to clone objects / arrays during setState in React
- setInterval with setState in React
- updating objects with setState in React
- React setState not working on first try, but works on second?
- How to use fetch() API in React to setState
- React JS: setState is late on last input
- react setState with dynamic key
- Do we still need functional setState way in react hooks?
- React Hooks: skip re-render on multiple consecutive setState calls
- Is it possible to stub out or spy on the setState method in React when doing unit tests?
- How do I avoid unused setState functions? Can React useState be created without a setter?
- React Native: setState not updating immediately when logging in console
- Issue of using e.target.value in React setState function
- Changing style property with setState in React
- Does react setState execute if the old and new value are the same?
- React Typescript how to setState
- react setState callback doesn't have the updated state
More Query from same tag
- create-react-app: how to load html before React renders
- How to build an edit form that depends on json
- What is the data type for date and time in PostgreSQL?
- importing sass variables from jsx file
- writing test case using jest-enzyme/react-testing library
- how to create store with react-redux
- React Module Parse Failed – react-map-gl
- How to update useReducer states in React?
- React Hook "React.useState" is called in function "form" that is neither a React function component nor a custom React Hook function
- React onClick event on <svg/> not working
- TextGeometry of Three.js with React not working
- Rendering a React component directly to HTML or Blade file
- how to use map in react to create multiple component?
- How to make an SVG scale without viewbox attribute?
- React: If a useState is updated, how can it be also non-updated at the same time?
- CSS display problem in mobile version for my map leaflet width just an header and footer
- Dispatch action every X second using Redux Saga
- React redux TypeError: Cannot read property 'id' of undefined
- Button click not working in ReactJs
- React Paginate, hide right pagination links after break and before next link
- React router v6 issue: how can I use match.params in element={ } as it replaced component={} How to pass match.params in the element
- How to add a priority to react components?
- Why clear method not exist on @testing-library/user-event
- Adding the function to remove products from the cart won't allow me to add more products
- It is not giving userid in url when i visit this route
- Error connection refused localhost:5000/user from another device
- Updating Formik State whilst using Headless UI "Listbox" (which manages its own state, internally)
- Next-auth: Props to page undefined although passed from getServerSideProps
- Rendering state json in React
- How to properly use Styled() with MUI V5