Hello everyone 👋, I hope you are doing great.
So, today you are going to learn all the basic concepts of React.useState
Hook.
The React.useState
is a function that accepts one argument, which is the initial state, and returns an array containing two values. The first value is the current state, and the second value is an updater function that allows you to update the current state.
We can name these two variables whatever we want, but a common convention is to choose a name for the current state and then prefix the set
in the front of the updater function.
Here is the sample code that uses the React.useState
Hook.
// function component
function Counter() {
const [count, setCount] = React.useState(0);
const increment = () => {
setCount(count + 1);
};
return <button onClick={increment}>+ {count}</button>;
}
Example
I hope you learned something from this article and if you have any doubts, please leave a comment. I will be delighted to answer all of your questions.
My name is Bipin Rajbhar and I am a software engineer at QuikieApps, and you can follow or connect to me on Twitter and Linked In
Resources
The Beginner's Guide to React
Epic React
Top comments (2)
If you change based on previous value setState(prevState => prevState + 1)
I save this for the advance react hooks series 😅.