Is it possible to create state without using an object inside the constructor?
I need to dynamically create new states inside the component on the fly. Any recommendations?
Is it possible to create state without using an object inside the constructor?
I need to dynamically create new states inside the component on the fly. Any recommendations?
The state object is literally just a Javascript object, so it is already dynamic.
If you want, you can modify it anywhere, anytime. But this completely breaks the good design pattern that React gives you -- single source of truth for data, and no mutating any state objects gives you a perfect history of every action that has taken place, making debugging a piece of cake.
This is why they encourage you to create an initial state, then use setState, which just creates a new copy while modifying the fields you specified.
Skip down to 'Using State Correctly': https://facebook.github.io/react/docs/state-and-lifecycle.html
If you need to 'dynamically create new states on the fly', is there any reason you can't define these in the constructor with initial values, whether or not you use them? I don't see any reason they would have to not exist at first, instead of just have an initial state. More detail about what you're trying to do would be helpful.
in case you was using typescript, i would define your state like this:
interface IComponentState {
dynamicState: any
}
and then you can assing any object to this dynamicState.... or any number of options to it...
in plain JS you even do not need to assign type, so it will be simplier - just assign empty object at start
Create state in inner method - render, is bad idea.
React recommended use only setState(), or 'state = ...' in constructor.
If the key (string) of the new state element is stored in variable newKey
, you can use
this.setState({ [newKey] : "new value" });
to dynamically add state.
I have found this useful when rendering a page based on a template where we don't know the elements to be rendered (and their state variable requirements) ahead of time.