DEV Community

Bharath kumar
Bharath kumar

Posted on

useState in React Hook

updating the screen:
first you import the useState

import { useState } from 'react';
Enter fullscreen mode Exit fullscreen mode

your component to “remember” some information and display it.
declare a state variable inside your component:

function MyButton() {
  const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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”

Top comments (0)