The Art of React Hooks: Part 1 - Mastering useState for Effortless State Management
I thought to write a series to explain all the React hooks. And this is the first blog of the series that will explain useState
hook in detail.
PermalinkWhat exactly is useState hook?
The React useState
hook is used to track state
in a function component.
State refers to the various variables that store some kind of data needed for our application.
When you use the useState
hook in React, you can create variables called state variables and set their initial values. These state variables are special because React remembers their values even when the component re-renders. React also provides functions that allow you to update these state variables.
Think of state variables as a way to store important data for your application. For example, you can use a state variable to keep track of user input, store data fetched from an API, or hold any other information that needs to change over time.
PermalinkLet's see an example to have a better understanding:
I will create a basic application that displays a number and two buttons that can be used to increase and decrease the value of that number.
The useState
hook will be used here for the number and an associated function that will be used to change the value of that number.
Step 1: Create a new folder and open that folder in VS Code.
Step 2:
Open the terminal and type the following commands one by one to set up and run your React application:
yarn create vite
Then, run the command npm i
to install the required dependencies.
Now, to run the project type the command: yarn dev
Your browser would open up showing a screen like this.
Step 3:
Now, next task is to edit the App.jsx
file inside the src
folder.
Include the following code in the App.jsx
file:
import { useState } from 'react'
import './App.css'
function App() {
const [count, setCount] = useState(0)
const handleIncrement = () => {
setCount(count+1)
}
const handleDecrement = () => {
setCount(count-1)
}
return (
<>
<div className='container'>
<button className='btn' onClick={handleDecrement}> - </button>
<div className='num'> {count} </div>
<button className='btn' onClick={handleIncrement}> + </button>
</div>
</>
)
}
export default App
To change the style include the following code in App.css
file:
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.container{
display: flex;
flex-direction: row;
}
.btn{
margin: 0px 40px;
width: 100px;
height: 50x;
}
.num{
font-size: 40px;
}
PermalinkCODE EXPLANATION:
In this code, I have created a basic application that displays a number and two buttons, one for decreasing the number and one for increasing the number.
The line const [count, setCount] = useState(0)
, creates a variable count
that has by default value 0, and setCount
is a function that can be used to change the value of count
variable.
Then, the two functions handleDecrement
and handleIncrement
are used to decrease and increase the value of count
variable respectively.
In handleDecrement
function, the line setCount(count-1)
decreases the value of the variable count
by 1.
Similarly, in handleIncrement
function, the line setCount(count+1)
increases the value of the variable count
by 1.
PermalinkOur app looks like:
You can click on the +
button to increase the value of the variable count
, and the -
button is used to decrease the value of variable count
.
PermalinkWith TypeScript:
You can assign a specific or multiple data types with the useState
hook.
The hook would look something like:
const [count, setCount] = useState<number | null>(null)
Here the variable count can either be a number
or null
.
Let's see the whole code for the same example that we saw before:
import { useState } from 'react'
import './App.css'
function App() {
const [count, setCount] = useState<number | null>(null)
const handleIncrement = () => {
setCount(count+1)
}
const handleDecrement = () => {
setCount(count-1)
}
return (
<>
<div className='container'>
<button className='btn' onClick={handleDecrement}> - </button>
<div className='num'> {count} </div>
<button className='btn' onClick={handleIncrement}> + </button>
</div>
</>
)
}
export default App
But this code will show an error:
It's because in the handleIncrement
and handleDecrement
functions, we are trying to increase the value of variable count
, which is null
by 1.
To fix that error, we can make use of TypeScript's Null Assertion operator !
.
Thus, the working code after fixing the error is:
import { useState } from 'react'
import './App.css'
function App() {
const [count, setCount] = useState<number | null>(null)
const handleIncrement = () => {
setCount(count!+1) //here's the change
}
const handleDecrement = () => {
setCount(count!-1) //here's the change
}
return (
<>
<div className='container'>
<button className='btn' onClick={handleDecrement}> - </button>
<div className='num'> {count} </div>
<button className='btn' onClick={handleIncrement}> + </button>
</div>
</>
)
}
export default App
Note how I changed setCount(count+1)
to setCount(count!+1)
setCount(count-1)
to setCount(count!-1)
.
The output initially would look like:
And it's because I have taken the initial value of count variable as null.
If you wanna read more about Null Assertion and other null and undefined related concepts in TypeScript, check out my other blog:
https://swapn652.hashnode.dev/typescripts-optional-chaining-nullish-coalescing-and-null-assertion-what-you-need-to-know
That's it for today. I hope you learned something new. You can reach out to me on: