React - You might not need that many states!

Bruno Noriller - Jun 26 '22 - - Dev Community

You probably know not to use one single state for everything a component needs.
But in avoiding that, sometimes you feel compelled to split the state in one for each thing you need.

But you don’t need to do that!

If you have things that change together, then you end up setting a “waterfall“ of events that could be bundled together.

The form example:

Let’s say you have this form example:

function FormExample(){
    ???

    return (
        <form>
            <input name="data1" />
            <input name="data2" />
            <input name="data3" />
        </form>
    )
}
Enter fullscreen mode Exit fullscreen mode

You can have it split into three states:

const [data1, setData1] = useState(data1Default)
const [data2, setData2] = useState(data2Default)
const [data2, setData3] = useState(data3Default)
Enter fullscreen mode Exit fullscreen mode

But you could also:

const [allData, setAllData] = useState(dataDefault)
// and then...
const updateData = (event) => {
    setAllData((oldState) => ({
        ...oldState, 
        [event.target.name]: event.target.value
    }))
}
Enter fullscreen mode Exit fullscreen mode

With this, as long as you name the inputs you can update all the state in one go.

And it doesn’t need to be a form, anywhere the data will always change together is a place you might not need to split.

And if one piece depends on another one, you would have a harder time dealing with it or having useEffects using the values as dependencies or risk having outdated data showing.

TIL: this works with nested data too!

The dependency array of hooks works with nested data [data.like.this] and not only that… even if you have data that might not be there it works!
So, you can have the state in one place and use [data?.optional?.chaining] instead of splitting or putting the entire object in the array with a if value then do stuff.


TLDR: Split if it makes sense for the data to be in different places, else, as long as it’s readable and maintainable… you might want to consider sticking to one state.


Cover Photo by Kelly Sikkema on Unsplash

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player