Menu

How Destructuring Is Used in React
📰

How Destructuring Is Used in React

DEV Community: frontend·Lokesh·11 days ago
#DpHbDzkD
#devtofrontend#devto#dev#destructuring#props
Reading 0:00
15s threshold

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 ;

Enter fullscreen mode

Exit fullscreen mode

Here:

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

Enter fullscreen mode

Exit fullscreen mode

useState() returns an array containing two values:

The current state value.

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.