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.
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}.
);
};The useState function takes an initial value and returns an array with two elements:
When the state changes, the component re-renders and the new value is displayed in the UI.
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.
useState hooks in one or more components.StrictMode.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.