Lifting state up

Share data between components through their parent.

When two components need the same data, move the state up to their closest shared parent. The parent passes the value down as a prop, and passes a function down so a child can ask for a change.

React (JSX)
import { useState } from "react";

function SearchBox({ query, onChange }) {
  return <input value={query} onChange={(e) => onChange(e.target.value)} placeholder="Search courses" />;
}

function CourseList({ courses, query }) {
  const shown = courses.filter((c) => c.toLowerCase().includes(query.toLowerCase()));
  return (
    <ul>
      {shown.map((c) => <li key={c}>{c}</li>)}
    </ul>
  );
}

export default function Courses() {
  const [query, setQuery] = useState("");
  const courses = ["React", "Python", "Java", "PHP", "JavaScript"];
  return (
    <>
      <SearchBox query={query} onChange={setQuery} />
      <CourseList courses={courses} query={query} />
    </>
  );
}

The filtered list is not stored in state. It is worked out from query and courses on every render, so it can never be out of date. Keep state as small as possible and calculate the rest.

The filter itself is plain JavaScript. Change query to "p" and press Run.

Expected output
["Java","JavaScript"]
โ† FormsuseReducer โ†’