Getting started with useState hook in React JS

Getting started with useState hook in React JS

Hooks are a new concept in React 16.8 (current version is 17.0.1 as on Nov 26, 2020). It helps us in using the state in your component without writing the class. This post will help you in getting started with Hooks in React Js.

What is Hooks in React?

Hooks are the concept in React, which allows you to use states and some other features of React which was earlier available only in the class-based component.

So, after the introduction of Hooks in React, you'll be able to use the state and some other features inside your functional component, which was not possible earlier without writing class-based components.

One of the best examples of hooks in react is useState function.

The useState hook

State in react holds the property value in a component. When the state changes, the component re-renders.

To use states in our functional component, we use the useState hook and, it helps us to eliminate the use of class in our code.

Unlike class, the state shouldn't have to be an object while using useState hook. It can contain any data type.

The useState method takes an initial value of state as the parameter and, it returns an array which contains two elements, the initial value of the state and a function to make changes or modify the state's initial value.

Let's see useState hook in action.

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me

Here the useState will return two value, one is the initial value of count and another is function to change the value of count.

Now we are able to use the variable count inside the p tag. It will show the value of count instead of the text count.

<p>You clicked {count} times.</p>

Since the initial value of our count is 0, it will show, You clicked 0 times.

Now, we are calling the setCount method inside the onClick of the button and we are incrementing the value of the count once the button is pressed.

This will increment the value of the count and will update the UI.

This was all about useState Hook in a react app'. If you found my application helpful, please mark recommend below in the comments section below.

I hope you liked my post on Getting started with useState hook in React JS and if you found my post helpful, please share it with your friends and if you have any doubt, feel free to comment below and I'll try to solve your problem ASAP.

Thanks for your time and I'll meet you in my next post. Take care and happy coding🙂!

Did you find this article valuable?

Support Pratik Sah by becoming a sponsor. Any amount is appreciated!