useState in react js

RumaisaRumaisa
2 min read

What is useState in react js?

useState() is simply a hook in react js which is defined inside functional components. It is used to track the state of the function component.

To use useState hook first of all we have to import it

import React , {useState} from 'react'

syntax

const [stateVariable,setStateVariable]=useState(initialState);

Syntax Explanation:

[stateVariable,setStateVariable] This is known as array destructuring which is a special javascript feature.useState returns an array with two values the first one is the variable that defines the current state and the other is a function that set the state of the variable.

Example

import { useState } from 'react'

import './App.css'

function App() {
  const [color, setColor] = useState('Red')
const changeColorHandler=()=>{
  setColor('blue')
}
  return (
    <>

  <button onClick={changeColorHandler} style={{backgroundColor:color}}>Change color</button>
    </>
  )
}

export default App;

Example explain

In this example, I show you how to change the background color of a button using useState .The initial color of the button is red on clicking the button the color changes from red to blue.

useState Hook Rules

  • Must define inside of the functional component.

  • Cannot be defined inside of class-based components.

  • Cannot be used inside of conditional statements.

Must be defined at the top of the function component just like other react hooks.

Your task!!

Change the text of the button to a new text.

1
Subscribe to my newsletter

Read articles from Rumaisa directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rumaisa
Rumaisa