useState Hook in React
In the previous chapter, we learned what state is. Now let's meet the tool that brings state to life in functional components: the **useState** hook.
What is the useState Hook?
`useState` is a React Hook that lets you add state to functional components. It's one of the most commonly used hooks and is the foundation of interactive React applications.
Hooks are special functions that let you "hook into" React features. `useState` is the hook for adding state.
Syntax of useState
const [state, setState] = useState(initialValue);Let's break this down:
- state: The current state value (like a variable).
- setState: A function to update the state.
- initialValue: The starting value of your state (can be a number, string, boolean, array, object, etc.).
The `useState` hook returns an array with exactly two elements. We use array destructuring to give them names.
Simple Example: Counter
import React, { useState } from 'react';
function Counter() { <!-- Declare state variable 'count' with initial value 0 --> const [count, setCount] = useState(0);
<!-- Function to handle button click --> function handleClick() { setCount(count + 1); }
return ( <div> <p>You clicked {count} times</p> <button onClick={handleClick}>Click me</button> </div> );}How It Works
- When the component first renders, `useState(0)` returns `[0, setCount]`. So `count` is `0`.
- When you click the button, `handleClick` calls `setCount(count + 1)`.
- This tells React to update the state and re-render the component.
- On the next render, `useState(0)` returns `[1, setCount]` (React remembers that the state is now 1).
- The UI updates to show "You clicked 1 times".
Using State with Different Data Types
String:
const [name, setName] = useState('John');Boolean:
const [isLoggedIn, setIsLoggedIn] = useState(false);Array:
const [items, setItems] = useState(['apple', 'banana']);Object:
const [user, setUser] = useState({ name: 'John', age: 25 });Rules of Using useState
- Call at the Top Level: Don't call hooks inside loops, conditions, or nested functions. Always call them at the top level of your component.
- Call from React Functions: Only call hooks from React functional components or custom hooks.
- State Updates are Async: The `setState` function doesn't update the state immediately. It schedules an update.
Multiple State Variables
You can use `useState` multiple times in a single component to manage different pieces of state.
function UserProfile() { const [name, setName] = useState(''); const [age, setAge] = useState(0); const [isActive, setIsActive] = useState(false); <!-- ... -->}Two Minute Drill
- `useState` is a React Hook that adds state to functional components.
- It returns an array with two elements: `[currentState, setStateFunction]`.
- The `setState` function is used to update the state and triggers a re-render.
- You can use `useState` with any data type (number, string, boolean, array, object).
- Always call `useState` at the top level of your component, never inside loops or conditions.
- You can have multiple `useState` calls in one component for different pieces of state.
Need more clarification?
Drop us an email at career@quipoinfotech.com
