This content originally appeared on DEV Community and was authored by Kyaw Min Tun
In ReactJS, useState
is a Hook that allows you to add state management to functional components. Before Hooks were introduced, state could only be managed in class components, but useState
enables functional components to also handle state.
How useState
Works:
- Syntax:
const [state, setState] = useState(initialState);
-
state
: This is the current state value. -
setState
: This is a function that allows you to update the state. -
initialState
: This is the initial value of the state. It can be a primitive value, object, array, etc.
Example:
import React, { useState } from 'react';
function Counter() {
// Declare a state variable called 'count' with an initial value of 0
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Explanation:
- Initially,
count
is set to0
(theinitialState
). - When the button is clicked,
setCount
is called, which updates thecount
state by incrementing it by1
. - The component re-renders with the updated
count
value.
Key Points:
- State Preservation: React preserves the state between re-renders, so the component will remember the state value even after it re-renders.
-
Multiple State Variables: You can call
useState
multiple times in a single component if you need more than one piece of state.
Hooks like useState
enable more complex stateful logic in functional components, making them a powerful alternative to class components.
This content originally appeared on DEV Community and was authored by Kyaw Min Tun
Kyaw Min Tun | Sciencx (2024-08-13T15:33:36+00:00) What is useState in ReactJS?. Retrieved from https://www.scien.cx/2024/08/13/what-is-usestate-in-reactjs-2/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.