DEV Community

Cover image for Basic Hooks: useState
Bipin Rajbhar
Bipin Rajbhar

Posted on

9 4

Basic Hooks: useState

Hello everyone 👋, I hope you are doing great.

So, today you are going to learn all the basic concepts of React.useState Hook.

The React.useState is a function that accepts one argument, which is the initial state, and returns an array containing two values. The first value is the current state, and the second value is an updater function that allows you to update the current state.

We can name these two variables whatever we want, but a common convention is to choose a name for the current state and then prefix the set in the front of the updater function.

Alt Text

Here is the sample code that uses the React.useState Hook.

// function component
function Counter() {
  const [count, setCount] = React.useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return <button onClick={increment}>+ {count}</button>;
}
Enter fullscreen mode Exit fullscreen mode

Example

I hope you learned something from this article and if you have any doubts, please leave a comment. I will be delighted to answer all of your questions.

My name is Bipin Rajbhar and I am a software engineer at QuikieApps, and you can follow or connect to me on Twitter and Linked In

Resources
The Beginner's Guide to React
Epic React

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (2)

Collapse
 
ivan_jrmc profile image
Ivan Jeremic

If you change based on previous value setState(prevState => prevState + 1)

Collapse
 
bipinrajbhar profile image
Bipin Rajbhar

I save this for the advance react hooks series 😅.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay