In React, props (short for "properties") are a way to pass data from a parent component to a child component. Think of props as the way we send information down to components so they can use it.
Destructuring is a JavaScript feature that allows us to extract values from an object and assign them to variables.
Props contain different values that you pass to a component, like text, numbers, or even functions! Normally, you would have to refer to each prop by its name, like props.age, props.location, etc. But destructuring is a shortcut that allows you to grab only the props you want, in a simpler way, directly.
As i've learned to code, I try to implement ways to write a cleaner and more concise code. I've found that destructuring of props is an important practice for having a cleaner and more readable code.
Here's how you would usually access props without destructuring in a functional component:
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
In the example above, props is an object, and we access name using props.name.
Now, let’s make the code cleaner using destructuring. Instead of accessing props.name, we can directly extract the name property from props object:
function Welcome({ name }) {
return <h1>Hello, {name}!</h1>;
}
Here’s what happens:
When you wrap the prop value in curly brackets {} like this: { name } you are destructuring! It takes the name property from the props object and creates a variable name that we can use directly in our function.
This is a shorter and cleaner way to write the code, especially when you have many props.
Why is this useful?
Provides for a cleaner code: Instead of writing props.name, you can just write { name }.
Less repetition: If you have several props, you don’t need to repeat props. every time.
Improves readability: Destructuring makes it clear which props are being used in the component.
Example with multiple props:
Let's say you have a component that takes multiple props:
function UserProfile({ name, age, location }) {
return (
<div>
<h2>Name: {name}</h2>
<h3>Age: {age}</h3>
<p>Location: {location}</p>
</div>
);
}
Here, name, age, and location are being destructured from the props object. Instead of writing props.name, props.age, and props.location, you just directly access these values.
Core Takeaway:
Destructuring props makes your code cleaner, easier to read, and more concise.
You don’t need to use the props keyword every time you want to access a prop if you destructure them in the function parameters.
Sources:
(https://react.dev/learn/passing-props-to-a-component)
(https://www.w3schools.com/react/react_es6_destructuring.asp)
(https://www.dhiwise.com/post/component-development-with-react-destructuring-props)
Top comments (0)