useState props

const [activeIndex, setActiveIndex] = useState(null);

Whenever you call useState in React, you get back two elements. The first value will always be its most recent state and the second value is the value you want to set state to.

The const above is called array destructuring and in our particular instance, it’s used to give us direct access to the first element (state) and second element (set state) of useState.

It shortcuts having to do the below:

const colors = ['red', 'green'];
const redColor = colors[0];
const greenColor = colors[1];

And you can shortcut the above by simply doing:

const [redColor, greenColor] = colors;

Which is assigning the first Element in colors, to the variable redColor and the second element in colors, to the variable greenColor.

There are three steps to setting state in Class Components and in Functional Components.

Class Component

// Initialize in the constructor
state = { activeIndex: 0 };

// Reference
this.state.activeIndex;

// Update
this.setState({ activeIndex: 5 });

Functional Component

// Initialize
const [activeIndex, setActiveIndex] = useState(0);

// Reference
activeIndex;

// Update
setActiveIndex(5);
 

Greg DeMaderios

 
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments