Sub topic 1
Quick refresher: props and one-way data flow
Lifting state up depends on how data moves between components. This chapter reviews props and the one-way flow of data in React. Later chapters assume you have this model clearly in mind.
Prerequisites
This chapter assumes you already know:
- JavaScript functions, destructuring, and arrow functions.
- Basic JSX and function components.
- How to pass props to a component.
- How to call the
useStatehook. - How to handle events such as
onChange.
You do not need to know anything about sharing state between components. That is the subject of the rest of the tutorial.
What props are
Props (short for properties) are the inputs to a component. A parent component writes them as attributes in JSX. React collects them into one object and passes it as the first argument of the child function.
function Greeting({ name, excited = false }) {
return <h1>Hello, {name}{excited ? '!' : '.'}</h1>;
}
export default function App() {
return (
<>
<Greeting name="Ada" excited />
<Greeting name="Grace" />
</>
);
}Greeting receives { name: 'Ada', excited: true } in the first call and { name: 'Grace' } in the second. Destructuring in the parameter list is a shortcut for reading props.name and props.excited. The = false is a default that applies only when the prop is undefined. It does not apply when the prop is null.
Props can hold any JavaScript value: strings, numbers, booleans, objects, arrays, and functions. Anything other than a string literal goes inside curly braces, as in count={3} or user={currentUser}. A bare attribute such as excited is shorthand for excited={true}.
One-way data flow
React data moves in one direction: from parent to child, through props. A child cannot reach up and change a prop, and it cannot write to its parent's variables. The flow forms a tree, and values travel down its branches.
This restriction is deliberate. When a value on screen looks wrong, you can trace it upward. The component that rendered it received the value as a prop, and its parent passed that prop. At the top of the chain you find the component that owns the value. Because data cannot arrive from siblings or children, there are fewer places to look.
Props are read-only
A component must treat its props as read-only. React expects a component to behave like a pure function: given the same props, it returns the same JSX. Changing a prop inside the child breaks that expectation. It also does not work in the way beginners hope. A change to a local copy is invisible to the parent, and nothing triggers a re-render.
The common mistake is mutating an array or object prop:
function SortedList({ items }) {
// Wrong: sort() changes the array in place, so it changes the parent's array.
const sorted = items.sort();
return (
<ul>
{sorted.map(item => <li key={item}>{item}</li>)}
</ul>
);
}Array.prototype.sort mutates the array it is called on. The parent's array is now reordered, and the parent does not know it happened. Copy first:
function SortedList({ items }) {
const sorted = [...items].sort();
return (
<ul>
{sorted.map(item => <li key={item}>{item}</li>)}
</ul>
);
}
export default function App() {
const fruit = ['pear', 'apple', 'fig'];
return <SortedList items={fruit} />;
}Spreading into a new array leaves fruit untouched. The same rule applies to objects. Use { ...user, name: 'New' } instead of user.name = 'New'. In the next chapters, this habit also determines whether React notices a state update.
How props change over time
If props are read-only, how does a child ever show new data? The parent re-renders and passes new values. The child function runs again with a new props object.
import { useState } from 'react';
function Badge({ count }) {
return <span>Unread: {count}</span>;
}
export default function Inbox() {
const [unread, setUnread] = useState(2);
return (
<>
<Badge count={unread} />
<button onClick={() => setUnread(unread + 1)}>New message</button>
</>
);
}Here is what happens when you click the button:
- The click handler calls
setUnread(3). - React re-renders
Inbox, the component that owns the state. Inboxreturns<Badge count={3} />.- React calls
Badgeagain with{ count: 3 }and updates the text on the page.
Badge has no state and no setter. Its output is a function of what it receives. The value changed because the owner changed it, and the new value flowed down.
By default, a re-rendered parent re-renders all of its children, even if their props are identical. That is usually fast enough, and you should not worry about it until you measure a problem.
Props versus state
State and props look similar in the output, but they have different owners.
| Row | Props | State |
|---|---|---|
| Who sets it | The parent component | The component itself, through its setter |
| Can the component change it | No | Yes |
| Purpose | Configure a component from outside | Remember something between renders |
| Changes cause a re-render | Yes, when the parent re-renders with new values | Yes, when the setter is called |
A value is a prop in the child and state in whoever owns it. The same string can be state in App, then a prop in Header, then a prop again in a component inside Header. Lifting state up changes who owns a value, and it does not change what the value is.
The children prop
Every component also receives a special prop named children. It holds whatever JSX you place between the opening and closing tags.
function Card({ title, children }) {
return (
<section>
<h2>{title}</h2>
<div>{children}</div>
</section>
);
}
export default function App() {
return (
<Card title="Profile">
<p>Name: Ada</p>
<p>Role: Engineer</p>
</Card>
);
}children flows down like any other prop. The <p> elements are created by App, so App owns whatever data they display. Card only decides where they go. This pattern comes back in the chapter on alternatives to lifting.
Passing functions as props
A function is a value, so it can be passed as a prop. The parent defines a function and hands it to the child. The child calls it when something happens.
function Alert({ message, onDismiss }) {
return (
<div role="alert">
{message} <button onClick={onDismiss}>Dismiss</button>
</div>
);
}
export default function App() {
return <Alert message="Saved." onDismiss={() => console.log('dismissed')} />;
}The data still flows one way. The function travels down as a prop. The child does not change the parent's data directly, and it only calls a function the parent provided. The parent decides what the call does. The next chapter covers this in detail, because it is the way a child asks for a change in lifting state up.
Common errors with props
These mistakes come up often in practice:
- Calling a function instead of passing it. Writing
onClick={handle()}runshandleduring render and passes its return value. WriteonClick={handle}oronClick={() => handle(id)}. - Forgetting braces around destructuring.
function Greeting(name)receives the whole props object under the namename. You needfunction Greeting({ name }). - Passing a number as a string.
count="3"is the string'3', andcount={3}is a number. Arithmetic and===comparisons then behave differently. - Creating the object inline and expecting identity.
style={{ color: 'red' }}creates a new object on every render. This is fine for ordinary use, but it defeatsReact.memoand dependency arrays, which compare by reference. - Reading a prop that was never passed. A missing prop is
undefined. Rendering it shows nothing, and calling a method on it throws. Use defaults or check the parent. - Copying a prop into state.
useState(props.value)reads the prop only on the first render. Later changes to the prop are ignored. This is a major source of bugs in lifting state, and a later chapter covers it.
Why this matters for lifting state up
One-way flow limits what two sibling components can do. Siblings cannot send props to each other. A value can reach both of them only if a common ancestor holds it and passes it down. A child can influence the parent only through a function the parent gave it. These two facts lead directly to lifting state up:
- Data goes down as props.
- Requests for change go up as function calls.
- Shared values live in the closest component above everything that needs them.
Exercises
Exercise
A child component receives the prop tags, an array, and runs tags.push('new') in its body. The parent's list on screen does not update, but later the parent's array contains 'new' unexpectedly. Explain both observations and give a fix.
Show answer
The push mutates the parent's array in place, which is why 'new' appears in the parent's data. It does not call a state setter, so React never re-renders the parent and the screen does not update. The fix is to leave tags alone. If the child only needs an extended list for display, build a copy with [...tags, 'new']. If the list really must change, the parent should own it in state and pass down a callback that calls its setter with a new array.
Exercise
In this code, what does Greeting display, and why?
function Greeting({ name = 'friend' }) {
return <p>Hi, {name}</p>;
}
<Greeting name={null} />
Show answer
It displays "Hi, " with nothing after it. Default values apply only to undefined, and null is a real value, so name stays null. React renders nothing for null. To fall back for both, write name ?? 'friend' inside the component.