How do you guys reset a react component state valu...
# random
e
How do you guys reset a react component state value to it’s initial value? I want a nice dry way of doing it! 🙂
a
Use redux, and set
state=undefined
to reset to initialState 😄
b
Copy code
const initialState = {};
class Foo extends React.Component {
  state = initialState;
  reset() {
    this.setState(initialState);
  }
  ...
}
This only works if all the keys you use in state are defined in `initialState`; if you register more keys later then those won’t be removed.
There used to be a
replaceState
API but I think it’s removed or deprecated.
k
Maybe you can use
this.setState(() => {})
But maybe it might be a anti-pattern to add new keys to state inside your component(s).
nvm setState doesn’t overwrite missing keys…
h
a hoc that unmounts and mounts again maybe?
b
You could do
this.setState(Object.assign(mapKeys(this.state, () => undefined), this.initialState))