Introduction to React State
React state is a fundamental concept in building React applications. It allows us to manage and manipulate data within our components. State is an object that stores property values related to a component and is typically used for managing data that can change over time.
State is important in React because it allows us to create components that can dynamically update and render different values based on user interactions or other events.
For example, imagine we have a counter component that displays a number and a button. When the button is clicked, the counter value should increase by one. We can achieve this by using state to store the current value of the counter and update it when the button is clicked.
1// Counter component
2function Counter() {
3 const [count, setCount] = useState(0);
4
5 const incrementCount = () => {
6 setCount(count + 1);
7 };
8
9 return (
10 <div>
11 <p>Count: {count}</p>
12 <button onClick={incrementCount}>Increment</button>
13 </div>
14 );
15}
In this example, we use the useState
hook to create a state variable count
and a setter function setCount
to update its value. The initial value of count
is set to 0
. When the button is clicked, the incrementCount
function is called, which updates the count
value by adding 1
to it.
State is a powerful concept in React that enables us to create dynamic and interactive user interfaces. In the next lessons, we will explore different ways to use and manage state in React applications.