What is useState?
Potentially the most important React hook. It is important because it allows you to have state variables in functional components. According to the official documentation on React.org,
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
Prior to the addition of hooks we would need to write a class to store state and make a dynamic component.
How do you implement its functionality?
First, we must import the hook from react like so:
Before diving in it is important to note:
- Hooks can only be used inside functional components
- Hooks must execute in exact order in every component render. For example,
if (true) {
useState()
}
useState()
will give you and error:
React hook "useState" is called conditionally
In other words they can't be placed inside functions, conditionals, loops, etc. and must be at the top level.
How do you use it?
- Import useState.
- Initialize useState. The first argument in useState(initialState) is default state. For example, I want a user to click a grey button and the background color of an icon turn pink. default state is false. In other words, the user has not clicked the button; therefore, its initial state is false, the button hasn't been clicked and the background of the icon is grey.
import React, { useState } from 'react';
function iconColor() {
const [color, setColor] = useState(false);
}
When the function, useState(false) is invoked, it will return an array with two values. Our first value is state and our second value is a function that allows us to update the current state.
- Update state. Using the second value, again a function, we will update state.
function changeColor() {
const [color, setColor] = useState(false);
const iconGrey = () => setColor(false);
const iconPink = () => setColor(true);
return (
<>
<div className={color ? "icon-pink" : "icon-grey"} />
<button onClick={iconPink}>On</button>
<button onClick={iconGrey}>Off</button>
</>
);
}
for this example, "icon-pink" and "icon-grey" are icons that have preset colors.
Conclusion
This is the absolute basic use case of useState. If you would like to learn more about different use cases I would recommend checking out React.org's official documentation.
Top comments (0)