Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What is useState() in React?

I am currently learning hooks concept in React and trying to understand the below example.
import { useState } from 'react';

function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}


The above example increments the counter on the handler function parameter itself. What if I want to modify count value inside event handler function

Consider below example:
setCount = () => {
//how can I modify count value here. Not sure if I can use setState to modify its value
//also I want to modify other state values as well here. How can I do that
}

<button onClick={() => setCount()}>
Click me
</button>
by

3 Answers

akshay1995
useState is one of the hooks available in React v16.8.0. It basically lets you turn your otherwise non-stateful/functional components to one that can have its own state.

At the very basic level, it's used this way:

const [isLoading, setLoading] = useState(true);

This then lets you call setLoading passing a boolean value. It's a cool way of having "stateful" functional component.
hackeracademy
Informative post. I am a newbie in javascript, So, I think this will be very helpful for me.
sandhya6gczb
React hooks are a new way (still being developed) to access the core features of react such as state without having to use classes, in your example if you want to increment a counter directly in the handler function without specifying it directly in the onClick prop, you could do something like:


const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);


const setCount = () => {
setCounter(count + 1);
setMoreStuff(...);
...
};

and onClick:

<button onClick={setCount}>
Click me
</button>

Login / Signup to Answer the Question.