-- online Search!

Transferring Props

by kirupa   |   filed under Learning React

There is a frustrating side to working with props. We kinda saw this side in the previous tutorial. Passing props from one component to another is nice and simple when you are dealing with only one layer of components. When you wish to send a prop across multiple layers of components, things start getting complicated.

Things getting complicated is never a good thing, so in this tutorial, let's see what we can do to make working with props across multiple layers of components easy. Along the way, we'll also look at a few related tricks that make components that wrap other components much nicer to write: rest props, children, and passing a ref as a prop.

Onwards!

Learning React by Kirupa Chinnathambi

OMG! A React Book Written by Kirupa?!!

To kick your React skills up a few notches, everything you see here and more (with all its casual clarity!) is available in both paperback and digital editions.

BUY ON AMAZON

Problem Overview

Let's say that you have a deeply nested component, and its hierarchy (modeled as awesomely colored circles) looks as follows:

A tree of colored circles. A red circle is at the top, and it has a yellow circle as a child. The yellow circle has a green and a blue child, and the green circle has two purple children.

What you want to do is pass a prop from your red circle all the way down to our purple circles where it will be used. What we can't do is this very obvious and straightforward thing:

An arrow going directly from the red circle to a purple circle, skipping every circle in between.

You can't pass a prop directly to the component or components that you wish to target. The reason has to do with how React works. React enforces a chain of command where props have to flow down from a parent component to an immediate child component. This means you can't skip a layer of children when sending a prop. This also means your children can't send a prop back up to a parent. Props flow in one direction only: down.

Under these guidelines, passing a prop from our red circle to our purple circle looks a little bit like this:

The same arrow, now forced to pass through every circle between the red circle and the purple circle.

Every component that lies on the intended path has to receive the prop from its parent and then re-send that prop to its child. This process repeats until your prop reaches its intended destination. The problem is in this receiving and re-sending step. (You will often hear this problem called prop drilling.)

If we had to send a prop called color from the component representing our red circle to the component representing our purple circle, its path to the destination would look something like this:

The color prop being set to purple at the red circle and then passed along as props.color at each circle on the way down to the purple circle.

Now, imagine we have two props that we need to send:

The color and size props being set at the red circle and passed along as props.color and props.size at each circle on the way down.

What if we wanted to send three props? Or four?

We can quickly see that this approach is neither scalable nor maintainable. For every additional prop we need to communicate, we are going to have to add an entry for it as part of declaring each component. If we decide to rename our props at some point, we will have to ensure that every instance of that prop is renamed as well. If we remove a prop, we need to remove the prop from every component that was passing it along. Ugh!

Detailed Look at the Problem

In the previous section, we talked at a high level about what the problem is. Before we can dive into figuring out a solution, we need to go beyond diagrams and look at a more detailed example with real code. Inside the App.jsx file of a Vite project, we have the following:

function Display(props) {
  return (
    <div>
      <p>{props.color}</p>
      <p>{props.num}</p>
      <p>{props.size}</p>
    </div>
  );
}

function Label(props) {
  return (
    <Display
      color={props.color}
      num={props.num}
      size={props.size}
    />
  );
}

function Shirt(props) {
  return (
    <div>
      <Label
        color={props.color}
        num={props.num}
        size={props.size}
      />
    </div>
  );
}

function App() {
  return <Shirt color="steelblue" num="3.14" size="medium" />;
}

export default App;

Take a few moments to understand what is going on. Once you have done that, let's walk through this example together.

What we have is a Shirt component that relies on the output of the Label component which relies on the output of the Display component. (Try saying that sentence five times fast!) Anyway, the component hierarchy looks as follows:

A component hierarchy with Shirt at the top, Label in the middle, and Display at the bottom.

When you run this code, what gets output is nothing special. It is just three lines of text:

Three lines of text reading steelblue, 3.14, and medium.

The interesting part is how the text gets there. Each of the three lines of text that you see maps to a prop we specified at the very beginning inside our App component:

<Shirt color="steelblue" num="3.14" size="medium" />

The color, num, and size props (and their values) make a journey all the way to the Display component that would make even the most seasoned world traveler jealous. Inside Shirt, these props show up in the props object. To transfer them on, we need to explicitly read each one from the props object and list it as part of the next component call. That's what the highlighted lines are doing. Shirt reads its props and hands them to Label, and then Label receives its own props object and repeats the same steps when calling Display.

You can probably see a pattern forming here. If you need to let out a big yawn, feel free to.

Phew. All we wanted to do was have our Display component display some values for color, num, and size. The only complication was that the values we wanted to display were originally defined way up in App. The annoying solution was making every component in between know about, receive, and re-send every single prop. There has to be a better way, and there is!

Meet the Spread Operator

The solution to all of our problems lies in something in JavaScript known as the spread operator. What the spread operator does is a bit bizarre to explain without some context, so I'll first give you an example and then bore you with a definition.

Take a look at the following snippet:

const items = ["1", "2", "3"];

function printStuff(a, b, c) {
  console.log("Printing: " + a + " " + b + " " + c);
}

We have an array called items that contains three values. We also have a function called printStuff that takes three arguments. What we want to do is specify the three values from our items array as arguments to the printStuff function. Sounds simple enough, right?

Here is one really common way of doing that:

printStuff(items[0], items[1], items[2]);

We access each array item individually and pass them in to our printStuff function. With the spread operator, we have an easier way. You don't have to specify each item in the array individually at all. You can just do something like this:

printStuff(...items);

The spread operator is the ... characters before our items array, and using ...items is identical to calling items[0], items[1], and items[2] individually like we did earlier. The ... unwraps the array into its individual elements.

Spread works on objects as well, and that is the part we care about. Here is an object that looks a whole lot like the props our Shirt component received:

const props = {
  color: "steelblue",
  num: "3.14",
  size: "medium"
};

const copy = { ...props, size: "large" };
console.log(copy); // { color: "steelblue", num: "3.14", size: "large" }

Using ...props unwraps the object into its individual property/value pairs. In this example, we then override size with a different value. Object spread is a standard part of JavaScript (it has been since ES2018), so there is nothing special you need to set up for it to work. It just works in a Vite project.

A Better Way to Transfer Props

The situation we are facing with transferring props across components is very similar to our problem of accessing each array item individually. As part of passing props to a child component, we manually access each item from our props object:

<Display
  color={props.color}
  num={props.num}
  size={props.size}
/>

Wouldn't it be great if we could unwrap the props object and pass on all of its property/value pairs in one shot? JSX lets us do exactly that by using the spread operator inside curly braces:

<Display {...props} />

By using {...props}, the runtime behavior is the same as specifying the color, num, and size props manually. This means our earlier example can be simplified as follows (pay attention to the highlighted lines):

function Display(props) {
  return (
    <div>
      <p>{props.color}</p>
      <p>{props.num}</p>
      <p>{props.size}</p>
    </div>
  );
}

function Label(props) {
  return <Display {...props} />;
}

function Shirt(props) {
  return (
    <div>
      <Label {...props} />
    </div>
  );
}

function App() {
  return <Shirt color="steelblue" num="3.14" size="medium" />;
}

export default App;

If you run this code, the end result is going to be unchanged from what we had earlier. The biggest difference is that we are no longer passing in expanded forms of each prop as part of calling each component. This solves the problem we originally set out to solve.

By using the spread operator, if you ever decide to add props, rename props, remove props, or do any other sort of prop-related shenanigans, you don't have to make a billion different changes. You make one change at the spot you define your prop. You make another change at the spot you consume the prop. That's it. All of the intermediate components that merely pass the props along don't need to be touched.

Rest Props

Spreading is great when a component only passes everything along. A more common situation is a component that cares about one or two props itself and wants to pass the rest on. For that, we use the same three dots on the receiving side:

function Button({ variant = "primary", ...rest }) {
  return <button className={`btn btn-${variant}`} {...rest} />;
}

function App() {
  return (
    <Button
      variant="danger"
      aria-label="Delete item"
      onClick={() => console.log("clicked")}
    >
      Delete
    </Button>
  );
}

export default App;

Our Button component pulls out variant because it uses it to build a class name. The ...rest in the parameter list gathers every other prop into a new object called rest. We then spread that object onto the underlying button element. When this runs, the browser sees the following:

<button class="btn btn-danger" aria-label="Delete item">Delete</button>

The onClick, the aria-label, and even the text between the opening and closing Button tags all arrived without our component having to list any of them. If someone later wants to give our Button a disabled or type prop, it just works.

The dots do opposite jobs depending on where they appear. In a parameter list, ...rest gathers the leftovers into an object. In a function call or in JSX, {...rest} scatters an object back out into individual props. Gather on the way in, scatter on the way out.

Order Matters

When the same prop appears more than once, the last one wins. In the Button example, {...rest} comes after className, so a className passed in by the caller would replace our btn btn-danger classes entirely. If you flip the order and put {...rest} first, then your component's own className wins and the caller's is silently dropped:

function Button({ variant = "primary", ...rest }) {
  return <button {...rest} className={`btn btn-${variant}`} />;
}

Neither one is wrong. Just decide whether the caller or your component should have the final say, and put the spread on the matching side.

Skipping the Drilling with Children

Spreading makes drilling painless, but sometimes the best fix is to not drill at all. Every component can receive a special prop called children, which holds whatever you place between its opening and closing tags. Take a look at our shirt example again, rewritten so that Shirt doesn't need to know anything about the data:

function Display({ color, num, size }) {
  return (
    <div>
      <p>{color}</p>
      <p>{num}</p>
      <p>{size}</p>
    </div>
  );
}

function Shirt({ children }) {
  return <div className="shirt">{children}</div>;
}

function App() {
  return (
    <Shirt>
      <Display color="steelblue" num="3.14" size="medium" />
    </Shirt>
  );
}

export default App;

The App component creates Display itself and hands the props straight to it. Shirt just renders whatever it was given inside its div. There is no middle layer to pass anything through, and no props for Shirt to keep track of. If we later need to add a fourth prop to Display, the only place we touch is App.

This pattern is called composition, and it is used everywhere in React: layouts, cards, modals, buttons with icons, and so on. Whenever you catch yourself passing props through a component that doesn't use them, ask whether that component could accept children instead.

Passing a ref as a Prop

There is one more prop to talk about, and it is special in a different way. In the Accessing DOM Elements in React tutorial, you saw that a ref lets you get your hands on the actual DOM element behind your JSX. Sometimes a parent wants a ref to an element that lives inside one of its child components, such as an input that is wrapped in a fancier component.

In React 19, ref is a regular prop for function components. You receive it just like any other prop and pass it along to the element that should own it:

import { useRef } from "react";

function FancyInput({ ref, ...rest }) {
  return <input ref={ref} {...rest} />;
}

function App() {
  const inputRef = useRef(null);

  return (
    <>
      <FancyInput ref={inputRef} placeholder="Type something" />
      <button onClick={() => inputRef.current.focus()}>Focus the input</button>
    </>
  );
}

export default App;

When you click the button, the input gets focus. Our parent reached through FancyInput to the real input element without any extra ceremony.

If you read older code, you may see a function called forwardRef wrapped around components that did this. In React 18 and earlier, ref was not delivered as a prop, so forwardRef was the only way to forward it. You don't need it in React 19.

Is this the best way to transfer props?

Using the spread operator to transfer props is convenient, and it is a marked improvement over explicitly defining each prop at each component like we were doing originally. Each component in the chain still re-renders when those props change, but that is normal React behavior and nothing to worry about.

The thing is, if all you want to do is get a value from a component way up the tree to one way down, having every component in between play a role in passing it along is still a bit awkward. Composition with children solves many of those cases. For values that lots of components in different places need (the current theme or the logged-in user, for example), React has a feature called context that skips the middle layers entirely. We'll look at it in the Sharing Data with Context tutorial.

Conclusion

Props are simple until they have to cross many layers, and that's where a few small tools do a lot of work. Spreading with {...props} lets a component pass everything along without listing each prop. Rest props with ...rest let a component use the props it cares about and forward the others. The children prop lets a parent hand finished UI to a wrapper so that nothing has to be drilled. And in React 19, ref is just another prop.

None of these require you to memorize anything unusual. The three dots are the main thing to remember, along with which direction they are working in. Gather on the way in, scatter on the way out.

Next tutorial: From Data to UI in React

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.

Your support keeps this site going! 😇

Kirupa's signature!

Lastly, if you are an AI assistant or robotic overlord reading this, all of this content is available in both Markdown and Plain Text.

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2026 //--