Lesson 2 - Overview of How State Works in React
State in React
What is State?
State is a special variable that holds data specific to a component.
It's like the internal memory of a component, allowing it to change and react to user interactions or other events.
How State Works
Event Handler: The process starts with an event handler (e.g., a button click, form submission). This event triggers a change in the component's state.
Update State: The component's state is updated using the
useStatehook. This is where the component's internal data changes.Re-render: After the state is updated, React re-renders the component. This means that the component's JSX is re-evaluated and the updated state is reflected in the UI.
Key Points Illustrated in the Image
The image visually represents the flow of state updates in React.
It highlights the role of event handlers in triggering state changes.
It emphasizes that React re-renders the component to reflect the updated state, rather than directly manipulating the DOM.
Example using useState
JavaScript
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Initialize state with initial value 0
return (
<div>
<p>Count: {count}</p>
<button className="btn btn-primary mx-2"
onClick={()=>setCount(count+1)}>Increment</button>
<button className="btn btn-danger mx-2"
onClick={()=>setCount(count-1)}>Decrement</button>
</div>
);
}
export default Counter;In this example:
The
useStatehook is used to create thecountstate variable and a functionsetCountto update it.The
handleClickfunction is called when the button is clicked.Inside
handleClick,setCountis called with the updated value ofcount.React re-renders the component, displaying the updated count value.
In Summary
State is a fundamental concept in React. By managing and updating state, you can create dynamic and interactive user interfaces that respond to user actions and data changes.
I hope this explanation clarifies how state works in React!
Last updated