DEV Community

Cover image for React Basics~useState/ count number~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

React Basics~useState/ count number~

  • The useState is a react hook that holds a state of the component.
    In this case, the state is a counter.

  • The + button increases the state of the counter. The - button decreases the counter.

・src/Example.js

import { useState } from "react";

const Example = () => {
  const [count, setCount] = useState(0);
  return (
    <>
      <CountResult title="count" count={count} />
      <CountUpdate setCount={setCount} />
    </>
  );
};
const CountResult = ({ title, count }) => (
  <h3>
    {title} : {count}
  </h3>
);

const CountUpdate = ({ setCount }) => {
  const countUp = () => {
    setCount((prev) => prev + 1);
  };
  const countDown = () => {
    setCount((prev) => prev - 1);
  };
  return (
    <>
      <button onClick={countUp}>+</button>
      <button onClick={countDown}>-</button>
    </>
  );
};

export default Example;
Enter fullscreen mode Exit fullscreen mode

・Here is the action of countup.

Image description

・Here is the action of countdown.

Image description

Top comments (0)