Array Destructuring on useState Hook

Jeffrey Martinez
2 min readMay 9, 2021

One of the features JavaScript ES6 is Array Destructuring and Object Destructuring. Let’s see how this is implemented!

Have you seen this line before?

const [counter, setCounter] = useState(0);

What are we doing exactly? Well this is called Array Destructuring! Let’s use a regular const variable instead of the array destructuring. Let’s also log this into our console and see what we get.

const counter = useState(0);

This is what we get:

We get an array of our initial value which is 0 and the second thing in the array is a function. To better understand this let’s create an array of colors.

const colors = ['red', 'green'];

To access each color we can use the index within the array:

colors[0]; 
// return 'red';
colors[1];
// return 'green'

Let’s reassign these colors to a new variable:

const redColor = colors[0];
const greenColor = colors[1];

This is very tidious and so much code to just reassign the elements to a new const. What can we do? Array Destructuring!

const [firstElement, secondElement] = colors

What are we doing here? Well, we are not creating an array. We are assigning new variables to the first and second elements within the colors array. If we log to our console the firstElement, we will get the first index of the the colors array which would be “red”, if we log the secondElement to the console, then we would be returning the second element of the colors array which would be “green”.

Back To Our useState Hook

Since we know that we have an array of the initial state and a function, lets invoke array destructing in order to reassign them into different variables.

const [counter, setCounter] = useState(0);

If we log the counter, we will get our initial state to be returned which would be 0, if we log the setCounter, we will receive the second element of the array, which would be the function.

Resources

--

--

Jeffrey Martinez

I am a graduate from Flatiron School for Software Engineer. Studied HTML, CSS, Ruby, Ruby on Rails, JavaScript, React, Redux, Sinatra, and Sqlite3