dorkycam
dorkycam

Reputation: 529

Is it bad practice to nest states in React?

I've been working on a project and have gotten help from a couple of people. One of them told me it would be a better idea to nest my states, and so I did. However, when I got help from someone else they had told me that nesting states is not a good idea and that I should avoid doing it. I don't have a lot of experience with this at all but I would like to do it the better/most practical way possible. Does anyone have any input?

Here's an example of what I meant by nested states:

constructor(props){
    super(props);
    this.state = {
        someGroup = [{
            somePartA: "",
            somePartB: [],
            someKey: uuid()
        }],
        somethingElse = "",
        anotherOne = "",
    }
}

And here's what I mean by not nested

constructor(props){
    super(props);
    this.state = {
        somePartA: "",
        somePartB: [],
        someKey: uuid(),
        somethingElse = "",
        anotherOne = "",
    }
}

Thanks in advance!

Upvotes: 3

Views: 1227

Answers (1)

mccambridge
mccambridge

Reputation: 1022

It's generally a good idea to keep your state shallow.

If you have a complex application, it's an even better idea to limit state to UI concerns and use a state container outside of the component like Redux, especially when the data you're keeping in state is more application data than local component concerns.

This is potentially a big topic with loads of opinion. If you haven't yet I would read up on React state design. Here are some articles. Keep in mind there's no single answer. But these should help you build a foundation.

Upvotes: 4

Related Questions