What is state in React?
State in React refers to an object that holds data which is specific to a component and can change over time. It allows components to create dynamic and interactive user interfaces by re-rendering when the state data is updated.
What is State?
At its core, state is a plain JavaScript object used to store data that a component needs to render and manage. Unlike props, which are passed down from a parent component and are immutable for the child, state is managed internally by the component itself and is mutable.
When the state of a component changes, React triggers a re-render of that component and its children. This mechanism is fundamental to building responsive and interactive user experiences, as it ensures the UI always reflects the latest data.
Key Characteristics of React State
- Mutable: State can be changed by the component that owns it.
- Local: State is private to a specific component and cannot be directly accessed by other components, except when explicitly passed down via props.
- Causes Re-renders: Any change to a component's state will trigger a re-render of that component and its child components.
- Asynchronous Updates: React may batch multiple state updates into a single re-render for performance, meaning state updates can be asynchronous.
Using State with the useState Hook
In functional components, state is managed using the useState Hook. This Hook allows you to add state variables to your functional components, providing a stateful value and a function to update it.
import React, { useState } from 'react';
function Counter() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0); // Initial state is 0
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
In the example above, useState(0) initializes the count state variable to 0. setCount is the function used to update the count. When setCount is called, React re-renders the Counter component with the new count value.
When to Use State
- User Input: For handling data from forms, input fields, or other interactive elements.
- UI State: Managing aspects of the user interface like whether a modal is open, a tab is active, or a section is collapsed.
- Fetched Data: Storing data retrieved from APIs or other asynchronous operations.
- Component-Specific Data: Any data that is unique to a component and changes over its lifecycle.