Object Destructuring in react
1 min readApr 8, 2021
What is Destructuring
Assume there is an object named Car
and you want to extract its properties, one way to do this is:
const car = {ID: '1',
brand: 'BMW',
model: '2021',};const id = car.ID;
const brand = car.brand;
const model = student.model;console.log(id); // 2
console.log(brand); // BMW
console.log(model); // 2021
But the thing is, there’s a lot of repetitive code in this example. So, to make things simpler, we can rewrite this code as:
const car = {ID: '1',
brand: 'BMW',
model: '2021',};const {ID, brand, model} = car
In react state destructuring could be:
// no destructuringconst users = this.state.users;
const counter = this.state.counter;// destructuringconst { users, counter } = this.state;
Functional stateless components always receive the props object in their function signature. Often you will not use the props but its content, so in nthis case destructure will be beneficial .
// no destructuringfunction Greeting(props) {
return <h1>{props.greeting}</h1>;}// destructuringfunction Greeting({ greeting }) {
return <h1>{greeting}</h1>;}