useState() in React Hooks

useState() in React Hooks

Hello Geeks, In this article we will learn about useState() in react hooks. useState() is an inbuilt hooks by react team. useState() React Hooks used to manage (set and update) state in your functional component in your react application.  In your functional component, you can import useState()  like below syntax.

import React, {useState} from 'react';

State management in functional component using useState() react hooks is totally different than we manage state in class based component.

use state in react hooks



Key points to remember for useState() in React Hooks

  • In class based component, we have to use object to define state, while in functional component use can set any primitive value to initial state.
  • In class based component, states are merged by itself, while in functional component you have merge state manually. (Don’t worry. Its very easy).
  • In class based component, we have single state. while in functional component we can manage multiple state.

Syntax for initializing state in Class bases component.


 state = {
    name: null,
	age: null
	
  };

Syntax for initializing state in functional component using useState().


const[inputname setInputName] = useState(null);l

const[inputage setInputAge] = useState(null);l

useState() always returns array with two value. First value is the current state and second element is the function to update the current state. That’s why we use array destructuring to get the current state and function to update in the state.



Example of useState() React Hooks in functional Component

Here is the example to initialize and update the state in functional component using useState() react hooks.


import React, { useState } from 'react';

export default props => {
  const [inputName, setInputName] = useState(null);

  const handleChange = (event) => {
    setInputName(event.target.value);
  };

  return (
    
<div>
      
<h1>useState() Example</h1>

      

{inputName}

      <input type="text" onChange={handleChange}/>

    </div>

  );
};

use state in react hooks

 

Hope, this article helps you to get the basic knowlegde of useState() in react hooks.

Thanks for reading. Happy Coding 🙂

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.