This content originally appeared on DEV Community and was authored by mona fakhri
When building interactive web applications with React, one of the most important concepts youβll encounter is state. State allows your components to βrememberβ information and update dynamically when something changes β for example, when a user clicks a button.
What is State?
In React, state is an object that stores data about a component. When the state changes, React automatically re-renders the component to reflect the updated data on the screen.
Think of state as a componentβs βmemory.β
Using the useState Hook
The most common way to manage state in functional components is with the useState hook.
Hereβs a simple example:
`import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
export default Counter;
`
** Explanation: **
useState(0) β initializes the state variable count with a value of 0.
count β holds the current state.
setCount β function to update the state.
When you click the button, setCount increases count by 1, and React re-renders the component.
State vs. Props
Props: Data passed into a component from its parent.
State: Data managed inside the component itself.
In short:
Props = external input
State = internal memory
Key Rules of State
Never modify state directly. Always use the updater function (setCount).
State updates are asynchronous. Donβt rely on state updating immediately after calling setCount.
This content originally appeared on DEV Community and was authored by mona fakhri