- Home
- /
- Tutorials
- /
- React Tutorial
- /
- Events and State Together
Handling Events
Events and State Together
When two components need the same value, it belongs to their closest shared parent. Moving it there is called lifting state up, and it is the answer to most "how do these talk to each other" questions.
A handler that updates state
The pattern is always the same: an event fires, the handler computes the next value, the setter stores it, React re-renders. Everything else in this chapter is a variation on those four steps.
Toggle, add, reset
jsx
function Panel() {
const [open, setOpen] = React.useState(false)
const [notes, setNotes] = React.useState([])
return (
<div>
<button onClick={() => setOpen((current) => !current)}>
{open ? "Hide" : "Show"} notes
</button>{" "}
<button onClick={() => setNotes((current) => [...current, `Note ${current.length + 1}`])}>
Add note
</button>{" "}
<button onClick={() => setNotes([])}>Clear</button>
{open && (
<ul>
{notes.map((note) => <li key={note}>{note}</li>)}
{notes.length === 0 && <li style={{ color: "#64748b" }}>No notes yet</li>}
</ul>
)}
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<Panel />)