Giter VIP home page Giter VIP logo

lifting-state's Introduction

Lifting State

How to share state between two sibling components?

To share between two sibling components we need to lift the state up which basically amounts to finding the lowest common parent shared between the two components and placing the state management there, and then passing the state and a mechanism for updating that state down into the components that need it.

Example

Our Initial App

function Name({
  name,
  onNameChange,
}: {
  name: string;
  onNameChange: ChangeEventHandler<HTMLInputElement>;
}) {
  return (
    <div>
      <label htmlFor="name">Name: </label>
      <input id="name" value={name} onChange={onNameChange} />
    </div>
  );
}

// 🐨 accept `animal` and `onAnimalChange` props to this component
function FavoriteAnimal() {
  // πŸ’£ delete this, it's now managed by the App
  const [animal, setAnimal] = useState("");
  return (
    <div>
      <label htmlFor="animal">Favorite Animal: </label>
      <input
        id="animal"
        value={animal}
        onChange={(event) => setAnimal(event.target.value)}
      />
    </div>
  );
}
// 🐨 uncomment this
// function Display({name, animal}) {
//   return <div>{`Hey ${name}, your favorite animal is: ${animal}!`}</div>
// }

// πŸ’£ remove this component in favor of the new one
function Display({ name }: { name: string }) {
  return <div>{`Hey ${name}, you favorite animal`}</div>;
}

function App() {
  // 🐨 add a useState for the animal
  const [name, setName] = useState("");
  return (
    <form>
      <Name name={name} onNameChange={(event) => setName(event.target.value)} />
      {/* 🐨 pass the animal and onAnimalChange prop here (similar to the Name component above) */}
      <FavoriteAnimal />
      {/* 🐨 pass the animal prop here */}
      <Display name={name} />
    </form>
  );
}

Suppose we have a new feature request for the Display component. We want to display the animal the user selects. But that state is managed in a β€œsibling” component, so we have to move that management to the least common parent (App) and then pass it down.

Lifting the state

function Name({
  name,
  onNameChange,
}: {
  name: string;
  onNameChange: ChangeEventHandler<HTMLInputElement>;
}) {
  return (
    <div>
      <label htmlFor="name">Name: </label>
      <input id="name" value={name} onChange={onNameChange} />
    </div>
  );
}

function FavoriteAnimal({
  animal,
  onAnimalChange,
}: {
  animal: string;
  onAnimalChange: ChangeEventHandler<HTMLInputElement>;
}) {
  return (
    <div>
      <label htmlFor="animal">Favorite Animal: </label>
      <input id="animal" value={animal} onChange={onAnimalChange} />
    </div>
  );
}
function Display({ name, animal }: { name: string; animal: string }) {
  return <div>{`Hey ${name}, your favorite animal is: ${animal}!`}</div>;
}

function App() {
  const [name, setName] = useState("");
  const [animal, setAnimal] = useState("");

  return (
    <form>
      <Name name={name} onNameChange={(event) => setName(event.target.value)} />
      <FavoriteAnimal
        animal={animal}
        onAnimalChange={(e) => {
          setAnimal(() => e.target.value);
        }}
      />
      <Display name={name} animal={animal} />
    </form>
  );
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.