React's useState hook

·

2 min read

The useState hook allows us to keep track of the state in a function component. The hook returns two values in the form of an array one is the current state and another is a function that updates it.

eg:

import './styles.css';
import { useState } from 'react';

export default function App() {

const [likeCounter, setLikeCounter] = useState(0);

function likeClikckHandler() {
var newLikeCounter = likeCounter + 1;
setLikeCounter(newLikeCounter);
}

return(
<div className='App'>
<h1>inside Outt!</h1>
<button onClick={likeClickHandler}> like Counter </button> {likeCounter}
</div>
);
}

first we need to import useState from react

import { useState } from 'react';

since useState is a hook it should be called inside the body of the function.

i.e. inside the function:-

export default function App() {
const [likeCounter, setLikeCounter] = useState(0);
}

here useState(0); will set the default value of the likeCounter to 0 and setLikeCounter will act as a setter function that will later update the value of likeCounter.

Now we want the value of likeCounter to increase only when the button 'Like Counter' is clicked so we will now increament the likeCounter inside the likeClickHandler function by assigning a new variable called newLikeCounter.

i.e. var newLikeCounter = likeCounter + 1;

setLikeCounter will update the value of likeCounter using the value of the newLikeCounter variable.

setLikeCounter(newLikeCounter);

return(
<div className='App'>
<h1>inside Outt!</h1>
<button onClick={likeClickHandler}> like Counter </button> {likeCounter}
</div>
);

We want the likeCounter to be displayed next to button so we will call the like counter next to button tag.

i.e. <button onClick={likeClickHandler}> like Counter </button> {likeCounter}