Sub topic 1
Lifting State Up in React
Prerequisites
You should know JavaScript functions, destructuring, arrow functions, JSX, function components, props, useState, and event handlers such as onChange. This chapter assumes you can read basic React components.
Props and one-way data flow
Props are inputs that a parent component passes to a child. Data normally flows downward through the component tree. A child can read its props, but it should not change them directly.
function Greeting({ name }) {
return <p>Hello, {name}</p>;
}
export default function App() {
return <Greeting name="Mina" />;
}App owns the string "Mina" and passes it to Greeting as the name prop. This one-way flow makes it clear where a value comes from.
State belongs to a component
State is data that a component remembers between renders. The useState hook creates state and a function that updates it.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}Here, Counter owns count. Updating it causes Counter to render again with the new value. State is private to the component that declares it unless that component passes the value to another component.
Passing callbacks down
A callback is a function passed to another function or component. A parent can pass an update function as a prop. The child then requests a change by calling that function.
function Field({ value, onChange }) {
return (
<input
value={value}
onChange={event => onChange(event.target.value)}
/>
);
}Field does not decide where the text is stored. It reports the user's action through onChange. The parent remains responsible for the data.
The problem: two components, two copies of the truth
Suppose two sibling inputs each use their own useState. Each input has a separate copy of the text. Updating one copy cannot automatically update the other.
The usual solution is to move the state into their closest common parent. The parent can then pass the same value and callback to both children. The next chapter develops this technique, called lifting state up.
Exercise
Why can two sibling components with separate state values drift apart?
Show answer
Each component owns an independent copy, so an update to one copy does not change the other.