October 15, 2024

“useState”: The most commonly used hook in React

Spread the love

Disclaimer:

I recently started my journey in React and I haven’t used class components in react. So my views are strictly for the functional components in react.


useState

useState is one of the most commonly used hooks in react, and also one of the most important ones. It enables you to add state function components. Calling useState inside a function component generates a single piece of state associated with that component. It’s especially useful for local component states, but larger projects might require additional state management solutions.


What is state? and why is it important?

In any react application there is a need to maintain some kind of a value, be it whether the button was clicked or not, the menu toggle is open or not, is the user logged in, etc. That value can be considered as a state for that particular object (button, menu toggle, user logged, and so on). Since we work with various react components which are rendered depending on the logic, we need to store that state value somewhere which isn’t affected by a new render, that’s where useState comes into the picture.

usestate syntax

Before we start using useState, we need to import it from react using import { useState } from ‘react’
Once imported we can simply use the hook by calling it: useState()


What are the arguments of useState?

useState takes the initial value of the state as an argument. This argument value can be of any type (boolean, string, number, or object). The initial value will be assigned only on the initial render. You can pass it directly as shown:
const buttonState = useState(‘off’)


What does useState return?

useState returns an array with two values:

  • Current value of the state
  • A function which can be used to update the state

We generally use array destructing to get both the values,
const [stateValue, setStateValue] = useState(‘off’)


How to update the state value?

We can use the useState provided function to update the set value: setStateValue(‘on’)
Here I updated the initial state value of ‘off’ to ‘on’ using the provided function.

However, the update function doesn’t update the value right away. Rather, it enqueues the update operation. That is why, if you try to print the updated value right after the update function, you will still see the old value as the state value. After, re-rendering the component, the argument of useState will be ignored and this function will return the most recent value.

You can also use the previous value to update the state, you just need to pass a function that receives the previous value and returns a new value:
setStateValue(prev => prev + value)


Using object as a state variable

As mentioned above you could assign any type of initial value to useState. We will be diving deeper into using objects as a state value since this can be a little confusing sometimes. There are two things you need to keep in mind while using an object as a state value:

  • The importance of immutability
  • The updating function returned by useState doesn’t merge objects

About the first point, if you update the state with the same value as the current state then react will not trigger a re-render.

And about the second point, consider you defined the initial state as {message:’ ‘, id: 1} but when you update the state, you only updated message value (because that’s what you need). React will not merge the old id value to the new state. In fact, the new state will look like this {message: ‘new message’}, the id property will be lost. So irrespective of what needs to be updated, you need to update the entire object in order to preserve the values. This makes useState very complicated to use when handling multiple states. We can create individual states as per our needs, but there are better options for that.


Feel free to drop in a comment if you would like to see some examples on how to use useState in practice. If you are interested in understanding how useReducer (more powerful state management in react) works, then you can read my post about it here.


Spread the love

4 thoughts on ““useState”: The most commonly used hook in React

  1. It is the best time to make some plans for the long run and it’s time to be happy. I have learn this publish and if I may I wish to recommend you few attention-grabbing issues or advice. Perhaps you could write next articles relating to this article. I want to learn even more issues about it!

  2. Hey, I think your website might be having browser compatibility issues. When I look at your website in Ie, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, very good blog!

  3. Hmm it looks like your site ate my first comment (it was super long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog writer but I’m still new to everything. Do you have any suggestions for first-time blog writers? I’d really appreciate it.

    1. Hey! I am super glad to know that you are enjoying the content. Honestly, this is my first time writing a blog as well so I don’t think I am in any position to give any suggestions. All I will say is to keep the content to your liking and don’t worry about what others want to read in the early stages. The main reason for me to start my blog was to motivate myself into learning new things constantly and also to keep my notes so that I can refer to them later.

Leave a Reply

Your email address will not be published. Required fields are marked *