~2 min read • Updated Oct 22, 2025
Introduction
In React, props are read-only and used to pass data from parent to child. But for data that changes over time, we use state. State is defined using the useState hook and allows components to update and re-render dynamically based on user interaction or other events.
Example: Managing Input State in the Search Component
Suppose we want to display the text a user types into an input field. A naive (non-working) approach might look like this:
let searchTerm = '';
const handleChange = (event) => {
searchTerm = event.target.value;
};This won’t work because React doesn’t know that searchTerm should trigger a re-render. The correct approach uses useState:
import * as React from 'react';
const Search = () => {
const [searchTerm, setSearchTerm] = React.useState('');
const handleChange = (event) => {
setSearchTerm(event.target.value);
};
return (
Searching for {searchTerm}.
);
};How useState Works
The useState function takes an initial value and returns an array with two elements:
- The current state value
- A function to update the state
When the state changes, the component re-renders and the new value is displayed in the UI.
Render vs Re-render
Each React component renders once initially. Then, whenever state or props change, the component and its children re-render. You can observe this by adding console.log() statements inside your components.
Key Notes About useState
- You can use multiple
useStatehooks in one or more components. - State can be a string, number, array, or object.
- In development, you may see logs twice due to
StrictMode. - React stores state in memory and cleans it up with garbage collection when components unmount.
Conclusion
State in React is a powerful tool for managing dynamic data. With useState, you can define, update, and display values that change over time. These updates trigger re-renders, allowing your UI to stay in sync with user interactions and application logic.
Written & researched by Dr. Shahin Siami