DEV Community

Cover image for Destructuring props in React
Angela Palaszewski
Angela Palaszewski

Posted on

Destructuring props in React

As with everything in coding, there is usually more than one way to reach the same outcome. Sometimes it's about best practice, but often times it comes down to personal preference.

Destructuring props is no exception to this.

What is a prop?

In React, "props" is a shorthand for properties, which are used to pass down data and functions from parent components to child components. Destructuring those props is a way to extract values from objects or arrays and assign them to variables.

Version One

Here's an example of destructuring props in the child component:


function MyComponent(props) {
  return (
    <div>
      <h1>{props.prop1}</h1>
      <p>{props.prop2}</p>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

In the example above, we extract prop1 and prop2 from props using destructuring, and then use them in the component's return.

This is helpful when you are passing down multiple functions and states, since the passed down prop will get pretty lengthy. This issue I find is that I tend to have to look back at the parent component to see exactly what I passed down and need to utilize.

Version 2

Here's an example of destructuring props as you pass them down:


function MyComponent({prop1, prop2}) {
  return (
    <div>
      <h1>{prop1}</h1>
      <p>{prop2}</p>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

In the example above, the component MyComponent takes an object as its argument, which contains two properties: prop1 and prop2. Instead of using props.prop1 and props.prop2, we can use destructuring to extract the values of these properties and assign them to variables of the same name.

I find this beneficial to be able to visualize everything I am passing down in one statement, so I know what I have used.

So which is better?

In both examples, destructuring props allows us to use the properties directly without needing to reference them via the props object. This can make the code more readable and concise. At the end of the day, it comes down to personal preference, since both of these options will give you the same results.

Which do you prefer?

Top comments (0)