DEV Community

Rakshambika
Rakshambika

Posted on

useState in React

What is useState?

  • useState is a React Hook that allows functional components to store and manage data that can change over time. Whenever the state changes, React automatically updates the UI to reflect the new value.
  • Before Hooks were introduced, state could only be managed in class components. The useState Hook made state management possible in functional components, making React code simpler and easier to maintain.

Why Do We Need useState?

In normal JavaScript, changing a variable does not automatically update the webpage.

let count = 0;

function increase() {
    count++;
    console.log(count);
}

Enter fullscreen mode Exit fullscreen mode

Even though the value of count changes, the UI will not re-render automatically.

React solves this problem using state. When state changes, React re-renders the component and updates the UI.


Syntax of useState:

const [state, setState] = useState(initialValue);
Enter fullscreen mode Exit fullscreen mode

Parameters:

  • state → Current value of the state.
  • setState → Function used to update the state.
  • initialValue → The initial value of the state.

Example : Counter Application

import { useState } from "react"; 
function Counter() 
{ 
const [count, setCount] = useState(0); 
const increase = () => { 
setCount(count + 1); 
};

return 
( <div> 
<h1>{count}</h1> 
<button onClick={increase}>Increase</button> 
</div> 
); 
} 

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Output

  • Initial value of count is 0.
  • When the button is clicked, setCount(count + 1) updates the state.
  • React re-renders the component and displays the updated value.

Rules of useState

  • Hooks must be called at the top level of a component.
  • Hooks cannot be called inside loops, conditions, or nested functions.
  • Hooks can only be used inside React functional components or custom Hooks.

Top comments (0)