The useState Hook in React
Finally, Something That Actually Makes Life Simpler
There’s always some new way to do things around the corner. Sometimes, its actually better.
A sigh of relief washed over me when I groked the useState
plus functional component combo.
Yes! This is actually simpler.
import { useState } from ‘react’;function philosophyComponent(){
const [profoundInsight, setProfoundInsight] = useState(“Beauty and Truth are One.”);
return (<div>{profoundInsight}</div>)}
So the syntax is slightly off-putting at first, but it’s actually super easy. What’s happening is the useState
is putting two variables into the component function’s namespace: a value and a function.
In this example, a variable called profoundInsight
is created, with a default value of “Beauty and Truth are One”.
A function called setProfoundInsight
is also exposed, and when called, this function will change the value of theprofoundInsight
variable.
Remember: never directly alter the state variable itself (profoundInsight
) in React, always use the setter function.
Let’s unpack the syntax a bit more, the general form is this: