Understanding React.useState

Leon Jamison
The Startup
Published in
2 min readMay 27, 2020

Have you ever started building a function component then later realized you needed to add state? Converting that function component into a class component can be extra time and essentially more work that could be prevented. You can get the same functionality in React today with using the useState hook. I call it working smarter, not harder!

What Does React.useState Allow You To Do…

React.useState allows you to create a single piece of state associated with that particular functional component in which it’s being called.

It is important to note that it is a hook and every hook starts with ‘use’. A call to ‘useState’ simply allows you too ‘use’ state inside a functional component. With hooks, the state can be any value we want it to be — in class components, state is always an object, with values assigned to that object. Each call to ‘useState’ creates a single piece of state, holding a single value of ‘any type’. Mind blowing right!

Example: Using ‘useState’ With an Array

Here, we have an array of random numbers. By clicking the button ‘Add Number’, we add a new random number to our array. (Remember state can hold any kind of value)

In this example, we’re calling useState with an initial value of an empty array [ ], and we’ve also defined a function called addItem.

Within this function, using the ES6 spread operator ..., we copy the existing items into the new array first, and then insert the new item at the end.

The state updater (setItems) doesn’t “merge” new values with old values, it simply overwrites the state with the new value given. This process is very different from how this.setState works with classes! BAM, just like that, you’ve created state within your function component without having to turn your component into a class component.

Before diving too deep into hooks, one should have a good understanding of how to pass components between the parent and child hierarchy within class and functional components first. Understanding this relationship would give you a good understanding of what is happening under the hood while using hooks as an awesome tool to create cleaner code. Remember, we always work smarter, not harder!

For a more information on understanding the useState hook, checkout this Codeevolution video below:

--

--

Leon Jamison
The Startup

Software Engineer — “Learn the rules like a pro so you can break them like an artist” — Pablo Picasso