So I've been learning the react framework for a while now.
While watching a tutorial I encountered the useState hook and I was kind of confused cause I was not familiar with the functionality, I was familiar with only classes this.state and this.setState.
So I did my research and read through react's documentation and to my surprise, I found it pretty straightforward.
P.S Always read the documentation
Since I've been deliberating on what my next article would be based on I decided to write on my new-found knowledge.
What's React State Hook
According to react's documentation - A Hook is a special function that lets you “hook into” React features. For example, useState is a Hook that lets you add React state to function components.
A hook is like a key that gives you access to some functionalities and features of React.
Before the introduction of React's hook, you would have to use a class component in other to have access to React state.
But with a hook, you can render a functional component and add a React state to it.
To simply use useState you have to import it from React
import React, { useState } from 'react';
After importing the useState you have to declare a state variable and a function to update the state. The useState takes one argument which is the initial state, the value could be any data (e.g string, array, object, number). useState also returns a pair of values (i.e an array) which contains the state and a function that updates the state.
import React, { useState } from 'react';
const [state, updateState] = useState(initialState)
The syntax used is JavaScript's array destructuring, since useState returns two values we're assigning the values into distinct variables.
Read more about array destructuring
A Simple Application of useState
/* Let's say I have a function component in which I need to monitor the no of clicks or views on a post
*/
import React, { useState } from 'react';
const [clicks, updateClicks] = useState(0)
function () => {
return (
<div>
<a href="" onClick={() => updateClicks(clicks + 1)}>Viewed {clicks} times</a>
</div>
)
}
So every time the link is clicked, updateClicks updates the no of clicks.
This was a short article.
For further reads check out React's Documentation
Thanks for reading 😃
Feel free to share your thoughts on React's state hook 🙂
I'm still learning 🤗