Skip to content

Complex state

So far, we've seen how we can store numbers and strings in React state. In many real-world cases, however, our state will be in a more complex shape, like an object or an array.

For example: a while back, I built a gradient generator tool. Users can select 2 to 5 colors, and we'll use that state to generate a gradient.

How would you track the state for the colors?

In my case, I created a colors state variable. It holds an array of strings:

const [colors, setColors] = React.useState(['#FFD500', '#FF0040']);

React doesn't care what type our state is. We can store numbers or strings or arrays or objects. We can even store functions in state if we want!

But there's a catch: React state changes have to be immutable. When we call setColors, we need to provide a brand new array. We should never mutate arrays or objects held in state.

Immutability is a big topic in JavaScript, and one we'll chip away at in the lessons ahead, and throughout the course.