![cover](/_app/immutable/assets/space_cover.h45XWM0x.jpg)
Demystifying React useState
Published at May 12, 2020
Hereâs a quick explaination on Reactâs useState! My assumption is you are familiar with how class components work in React, so Iâll explain what the hooks equivalents are đ
Letâs get straight to it
useState vs setState
In React Class Components, there is this concept of two types of components. One is a stateful component, and another is a stateless component. The general principle is you have state in components where it makes sense.
For instance, if you have a <Footer>
component, it doesnât really need to hold any variables of interest. But, if youâre building a task management
tool like trello, youâll want to store something for the tasks
, users
, etc.
Letâs jump into code đ
Hereâs a simplified example
import react from "react";
class TrelloBoard extends React {
state = {
boardTitle: "Hello Board!";
}
}
Note - you do not need constructor functions in React, since babel transpiles it for you behind the scenes
In our state, we have boardTitle
which is in the form of a string
Letâs say I modify the task boardâs title. It calls a function of modifyBoardTitle
import react from "react";
class TrelloBoard extends React {
// state is above
modifyBoardTitle(newTitle) ({
this.setState({
boardTitle: newTitle
})
}
render(){
return (
<button onClick={() => this.modifyBoardTitle("BrownFox")}>Click me!</button>
)
}
}
When we click this button, it converts the boardTitle
variable to âBrownFoxâ.
Okay enough class stuff, letâs go to hooks! Hereâs the equivalent using useState
import {useState} from "react";
const TrelloBoard = () => {
const [boardTitle, setBoardTitle] = useState('');
render (
<button onClick={() => setBoardTitle("BrownFox")}>Click me!</button>
)
}
The equivalent in hooks is much simpler, as itâs just a getter and setter with no side-effects. Letâs see how this part works:
const [boardTitle, setBoardTitle] = useState('');
It works as follows:
- The first argument is the name of the variable,
boardTitle
- The second argument is the name of the function that will modify
boardTitle
, in this case -setBoardTitle
useState('')
-> this sets an initial stateValue of''
We abstracted away the need for a function (in this case, modifyBoardTitle
).
This makes it easier to maintain in the long run đ
I made another article on useEffect
as well that you may find helpful