UseState is Easy.
The basics
It's simple. React's useState hook stores state.
You define it with a state name and a function for updating the state, define a default state (or not, whatever), and then call the updater function whenever you want to update it. Simple.
Here,
const [count, setCount] = useState(0);
Here,
count is the state variable, and setCount is the updater or "set" function, which is called to update the state.Count can then be changed by calling
setCount like this:setCount(newValue);
Each time the state is changed, the entire component will be re-rendered.
With Typescript
Great news! You don't need to explicitly type this.
Ready for some real developer jargon? useState is designed with type inference.
What does that mean? No one knows what it means, but it's provocative.
No, actually, we do know what it means. It means that Typescript is clever enough to look at what type you set the state variable to initially, and just use that, forever.
Here's an example
const [count, setCount] = useState(0);In this case, typescript will infer that
count should be a number, forever.That means that if you fuck around and try to call
setCount with a string, you'll find out, and Typescript will moan at you.onClick={() => setCount("test") //attempting to set count to stringHere's the error:
Argument of type 'string' is not assignable to parameter of type 'SetStateAction<number>'.
But what if I want to be able to change the state's type?
Simple, when defining the `count` state...
Instead of this:
const [count, setCount] = useState(0);Do this:
const [count, setCount] = useState<string | number>(0);Now
count can be either a string or a number.