Cover Image for What is the useState in ReactJS
203 views

What is the useState in ReactJS

The useState is a hook in React.js that allows functional components to manage state. Prior to the introduction of hooks in React (before version 16.8), state management was primarily done using class components and the setState method. Hooks like useState provide a more concise and intuitive way to manage state in functional components.

Here’s how you can use the useState hook in a functional component:

TypeScript
import React, { useState } from 'react';

function Counter() {
  // useState returns an array with two elements:
  // 1. The current state value.
  // 2. A function to update the state.
  const [count, setCount] = useState(0);

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

export default Counter;

In the example above, the useState hook is used to initialize a state variable called count with an initial value of 0. The hook returns an array where the first element is the current state (count) and the second element is a function (setCount) to update that state.

When the button is clicked, the increment function is called, which uses setCount to update the count state. React will then re-render the component, reflecting the updated state.

In summary, useState is a fundamental React hook that allows functional components to manage their own state, making it possible to create dynamic and interactive user interfaces without using class components.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS

  • Ester Hamilton

    Ester Hamilton

    Howdy! This blog post could not be written any better! Reading through this post reminds me of my previous roommate!

    He always kept preaching about this. I am going
    to forward this post to him. Fairly certain he’ll have a great read.
    Many thanks for sharing!

  • TechThunder

    TechThunder

    Thank you so much for valuable feedback.

Write a Comment