React Hook — useState

Irit Kushwaha
GDSC UMIT
Published in
3 min readAug 18, 2021
GDSC

useState is one of the most common React Hooks which every ReactJS developer should know. But using useState the precise way is not as easy as you might think. Today, I will go through some notes which I feel many newbies go wrong when managing useState and solutions to get rid of those issues and I’ll try to share my point of view and my acquaintance about it.

Quick Overview 🚀

I feel we should start with some basics about useState. We all know that useState is a React Hook that allows you to add React state to function components. Using the useState hook inside a function component, you can create a chunk of state without swapping to class components.

Syntax: The syntax of useState is very simple

setCounter

useState(0) retrieves a tuple where the initial parameter count is the current state of the counter and setCounter is the method that allows us to update the counter’s state. It accepts a new state value and enqueues a re-render of the component.

setCounter(newState)

We can use the setCounter method to update the state of count anywhere. During subsequent re-renders, the initial value returned by useState will always be the most recent state after applying updates.

The idea with hooks is that we can keep our code more functional and avoid class-based components if not desired/needed.

Dive deep into useState

🔴 Declaring state in React

useState is a named export from react. You can import it just by writing useState.

import

In a class component, we initialize the state i.e count to 0 by setting this.state to { count: 0 } in the constructor:

class comp.

In a function component, we call the useState Hook directly inside our component:

function comp.

🔴 useState : Reading State

In a class component, if we want to display the current count in a class, we read this.state.count

In a function component, we can directly use count

🔴 useState : Update state

The second element returned by useState is a function that takes a new value to update the state variable.

In a class component, we need to call this.setState() to update the count state:

In a function component, we have setCount and count as variables

Summarize 🙇

Let’s Recap the line by line code that we have learnt above

Rules for using useState ✍

  • Only call Hooks at the top level
  • Only call Hooks from React functions

Conclusion

Okay, so I’ve gone through some information about useState. There are many more cases you should notice when using useState to make your app work the promising way it could. So keep learning :)))

Thank you 😄

--

--