Destructuring assignment is an ES6 feature that allows you to extract properties from objects, or items from arrays, and bind them to distinct variables.
In React, you will use destructuring constantly. It drastically cleans up your code, making components much easier to read, especially when dealing with component props and state.
Before ES6, if you had an object and wanted to extract its properties into variables, you had to assign them one by one.
const vehicle = { brand: 'Ford', model: 'Mustang', type: 'car' }const brand = vehicle.brand; const model = vehicle.model;
With destructuring, you can accomplish the exact same thing in a single line of code by using curly braces {}.
const vehicle = { brand: 'Ford', model: 'Mustang', type: 'car' }// Destructuring the object const { brand, model } = vehicle;
console.log(brand); // Outputs: Ford
Notice how the variable names inside the {} exactly match the property names inside the object. The order does not matter!
You can also destructure arrays. Instead of curly braces, you use square brackets []. With arrays, the order does matter because arrays don't have property names, just indexes.
const vehicles = ['mustang', 'f-150', 'expedition'];// Destructuring the array const [car, truck, suv] = vehicles;
console.log(truck); // Outputs: f-150
(Fun Fact: If you've used React Hooks like useState, you are already using array destructuring! const [count, setCount] = useState(0) is array destructuring in action).
The most common place you will see destructuring in React is when passing and receiving props inside functional components.
When a component receives props, it comes in as a single props object. You have to type props. before every value you want to access.
const UserProfile = (props) => { return ( <div> <h1>{props.name}</h1> <p>Age: {props.age}</p> <p>Location: {props.location}</p> </div> ); };
By destructuring the props object directly inside the function parameters, we can drop the props. prefix entirely. The code becomes beautifully clean.
// Destructuring right inside the parameter parentheses! const UserProfile = ({ name, age, location }) => { return ( <div> <h1>{name}</h1> <p>Age: {age}</p> <p>Location: {location}</p> </div> ); };
This pattern is considered an industry standard in React. It also immediately tells anyone reading your code exactly what props this component expects!
{} and relies on property names.[] and relies on index order.props object inside functional components, making JSX much cleaner.useState) rely completely on array destructuring syntax.Look at the following code: `const { title, author } = myBook;` What kind of destructuring is this?