How Destructuring Is Used in React

2026-11-05来源 dev.toEnglish

1. What Is Destructuring?

Destructuring allows us to extract values from arrays and properties from objects and store them in separate variables.

React uses destructuring in many places, especially with:

  • useState
  • Props
  • Objects
  • API data

2. Destructuring with useState

One of the most common examples is the useState Hook.

import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); return ( <div> <h1>{count}</h1>  <button onClick={() => setCount(count + 1)}> Increase </button>  </div>  ); } export default Counter; 

Here:

const [count, setCount] = useState(0); 

useState() returns an array containing two values:

  1. The current state value.
  2. A function to update the state.

We use array destructuring to extract these two values.

  • count stores the current value.
  • setCount updates the value.

3. Destructuring Props

Props are used to pass data from a parent component to a child component.

Let's understand how destructuring makes working with props easier.

Without Destructuring

function Student(props) { return ( <div> <h2>{props.name}</h2>  <p>{props.age}</p>  </div>  ); } 

Here, we use props.name and props.age to access the values.

With Destructuring

function Student({ name, age }) { return ( <div> <h2>{name}</h2>  <p>{age}</p>  </div>  ); } 

Both examples produce the same result.

Instead of writing props.name and props.age, we directly extract the properties.

4. Destructuring Props in Parent Components

Let's see how a parent component passes data to a child component.

function Student({ name, course }) { return ( <div> <h2>{name}</h2>  <p>{course}</p>  </div>  ); } function App() { return ( <Student name="Lokesh" course="React" /> ); } export default App; 

Output:

Lokesh React 

The Student component receives the props and extracts name and course using object destructuring.

5. Destructuring API Data

We can also use destructuring when working with API responses.

const user = { id: 1, name: "Lokesh", email: "lokesh@example.com" }; const { name, email } = user; console.log(name); console.log(email); 

Output:

Lokesh lokesh@example.com 

This is useful when an API returns an object containing many properties, but we only need a few of them.

6. Why Is Destructuring Useful in React?

Destructuring helps us:

  • Write cleaner component code.
  • Access props easily.
  • Extract values from useState.
  • Work with API response data.
  • Avoid repeatedly writing object property names.

原文:https://www.a8q9.cn/en/article/how-destructuring-is-used-in-react-cba5d1.html

相关文章