Add interactivity to components by managing state with the useState hook.
State is data that belongs to a component and can change over time. When state changes, React automatically re-renders the component with the new value.
useState hookimport { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
useState(0) returns a pair: the current value (count) and a setter function (setCount). Calling the setter triggers a re-render.
TypeScript infers the type from the initial value. You can also be explicit:
const [name, setName] = useState<string>("");
const [items, setItems] = useState<string[]>([]);
When the new state depends on the old state, pass a function to the setter:
setCount(prev => prev + 1); // always safe
Build a counter component that:
<p> elementThe tests will check the DOM, so make sure your buttons have the exact text shown above.
import { useState } from "react"; export default function App() { // Add state here return ( <div> {/* Display the count and add buttons */} </div> ); }