../courses.php
React
REACT103
90
State
Let a component remember information that can change on screen.
How does React remember changing information inside a component?
React uses state to remember values that can change while the user is using the page. When state changes, React updates the displayed interface.
Props send information into a component from the outside.
State is different. State belongs to the component and can change while the page is being used.
A counter, open menu, selected tab, form value, search text, or shopping cart count can all use state.
State is one of the reasons React feels alive. The interface changes when the data changes.
In modern React, function components commonly use the useState hook.
A counter with state
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<section className="counter">
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Add one
</button>
</section>
);
}
function App() {
return (
<main>
<Counter />
</main>
);
}
useState gives the component a state value and a function for changing it.
count is the current state value.
setCount is the function used to update the state.
useState(0) starts the count at zero.
When setCount runs, React re-renders the component with the new value.
Memory
State lets a component remember changing information.
Updates
React updates the screen when state changes.
Interaction
Buttons, forms, tabs, menus, and filters often need state.
Component ownership
A component should own state when that state only matters inside that component.
Plain variable that will not update the screen correctly
function Counter() {
let count = 0;
return (
<button onClick={() => count = count + 1}>
{count}
</button>
);
}
React state
const [count, setCount] = useState(0);
<button onClick={() => setCount(count + 1)}>
{count}
</button>
Ask ChatGPT: "Which values in this React component should be state, and which values should just be props or constants?" Then identify what can change on screen.
Import useState.
Create a state value called count.
Display count in JSX.
Add a button that calls setCount.
Click the button and explain why the screen changes.
Using a normal variable for data that should update the screen.
Changing state directly instead of using the setter function.
Creating state for values that never change.
Putting state too high or too low in the component tree.
Forgetting to import useState.
Use React state to remember changing information and update the interface when that information changes.
Login - Jit4All
Login
Welcome back to Jit4All