Interactive components with useState

최윤서·2024년 1월 12일

useState

With the updates in React 16.8, it is now able to use manage the states though it's functional component.

Let's make a counter component and render it in App.js.

import React from "react";

function Counter() {
  return (
    <div>
      <h1>0</h1>
      <button>+1</button>
      <button>-1</button>
    </div>
  );
}

Nothing happens yet, because there's no event or something to change anything.

Set the Event

import React from "react";

export default function Counter() {
  const onIncrease = () => {
    console.log("+1");
  };

  const onDecrease = () => {
    console.log("-1");
  };

  return (
    <div>
      <h1>0</h1>
      <button onClick={onIncrease}>+1</button>
      <button onClick={onDecrease}>-1</button>
    </div>
  );
}

Now I made the functions to be called when those are clicked. You should not call the function like this

onClick ={onIncrease()}

Becasue this makes the function to be called when rendered. So it can cause the infinite loop.

Now you can see the logs on the console.

Make it dynamic with useEffect

import React, { useState } from "react";

function Counter() {
  const [number, setNumber] = useState(0);

  const onIncrease = () => {
    setNumber(number + 1);
  };

  const onDecrease = () => {
    setNumber(number - 1);
  };

  return (
    <div>
      <h1>{number}</h1>
      <button onClick={onIncrease}>+1</button>
      <button onClick={onDecrease}>-1</button>
    </div>
  );
}

export default Counter;

}

In this code, you declare the variable 'number' and its setter 'setNumber' at once. So, if you press the button, the current state of count is shown on the console and printed on the screen. We are renewing the number by putting the value we want through its setter. like 'setNumber(number + 1);'.

profile
일 잘 하고싶은 기개디자이너

0개의 댓글