This content originally appeared on DEV Community and was authored by Bharath kumar
updating the screen:
first you import the useState
import { useState } from 'react';
your component to “remember” some information and display it.
declare a state variable inside your component:
function MyButton() {
const [count, setCount] = useState(0);
initial state of count is 0 if you change the state use setCount
function MyButton() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<button onClick={handleClick}>
Clicked {count} times
</button>
);
}
when you click the button the current state is updated using the setCount is increased.
If you render the same component multiple times, each will get its own state.
Hook:
Functions starting with use are called Hooks.useState is a built-in Hook provided by React.
export default function MyApp() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>Counters that update together</h1>
<MyButton count={count} onClick={handleClick} />
<MyButton count={count} onClick={handleClick} />
</div>
);
}
the button is clicked upadted the state count together.use the information pass down this is called props.
function MyButton({ count, onClick }) {
return (
<button onClick={onClick}>
Clicked {count} times
</button>
);
}
count and onclick is a props of parents component
it is pass the button.
The new count value is passed as a prop to each button, so they all show the new value. This is called “lifting state up”
This content originally appeared on DEV Community and was authored by Bharath kumar
Bharath kumar | Sciencx (2025-11-28T12:09:34+00:00) useState in React Hook. Retrieved from https://www.scien.cx/2025/11/28/usestate-in-react-hook/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.