AI Hints
Home›React Tutorial›Sharing State
React · Lesson 31 of 120

Lifting State Up

Share between siblings.

⏱ 2 min read▶ Video at 23:30🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Sometimes two components need the same state. A search box and a results list, for example. The answer is to lift the state up, into their closest common parent.

  • Two components
  • Same state
  • Lift it up

The search box and the results both need the query. So the query lives in App, their common parent. App passes it down to both, and gives the setter to the search box. We search for volt. Run it.

App.jsxjsx
import { useState } from "react";
const BIKES = ["Trail 500", "City 200", "Volt 7"];
function SearchBox({ query, onChange }) {
  return <input id="q" value={query} onChange={e => onChange(e.target.value)} placeholder="Search" />;
}
function Results({ query }) {
  const found = BIKES.filter(b => b.toLowerCase().includes(query.toLowerCase()));
  return <ul>{found.map(b => <li key={b}>{b}</li>)}</ul>;
}
export default function App() {
  const [query, setQuery] = useState("");
  return (
    <div>
      <SearchBox query={query} onChange={setQuery} />
      <Results query={query} />
    </div>
  );
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"type": "#q", "text": "volt"}]

Lifting state

Find every component that needs the state. Find their closest common parent. Move the state there. Then pass it down as props.

  1. Who needs it?
  2. Common parent
  3. Move state up
  4. Pass it down

Summary

When siblings share state, lift it into their closest common parent. Next, passing functions down.

Key takeaways
  • Common parent
  • State up
  • Props down
Next up: Passing Functions Down — child to parent