In React, we commonly use destructuring in two places:
Props Destructuring:
Props are used to pass data from parent components to child components.
Without destructuring:
App.jsx (Parent)
function App() {
return ;
}
export default App;
Student.jsx (Child)
function Student(props) {
return (
My name is {props.name}
My age is {props.age}
);
}
export default Student;
With destructuring:
Student.jsx
function Student({ name, age }) {
return (
My name is {name}
My age is {age}
);
}
export default Student;
Both methods produce the same output:
- name extracts the name property.
- age extracts the age property.
- { name, age } is object destructuring.
useState Destructuring:
This is another important example in React.
import { useState } from 'react';
function App() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>
Click Me
</button>
</div>
);
}
export default App;
Here:
const [count, setCount] = useState(0);
- count → Current state value.
- setCount → Function to update the state.
- useState(0) → Initial value is 0.
Why square brackets []?
Because useState() returns an array containing two values. We use array destructuring to extract them.
JavaScript vs React Destructuring:
JavaScript React
Extract values from arrays Extract values from useState()
Extract properties from objects Extract properties from props
Uses [] and {} Uses [] and {}
General JavaScript feature Uses JavaScript destructuring
Top comments (0)