Hook 사용

Seungsoo Lee·2022년 7월 23일
0

Front-End

목록 보기
9/11
  • custom hook인 useCounter()
import React, { useState } from "react";

function useCounter(initialValue) {
	const [count, setCount] = useState(initialValue);

	const increaseCount = () => setCount((count) => count + 1);
	const decreaseCount = () => setCount((count) => Math.max(count - 1, 0));

	return [count, increaseCount, decreaseCount];
}

export default useCounter;
  • hook 사용 부분
import React, { useState, useEffect } from "react";
import useCounter from "./useCounter";

const MAX_CAPACITY = 10;

function Accommodate(props) {
  const [isFull, setIsFull] = useState(false);
  const [count, increaseCount, decreaseCount] = useCounter(0);
  
  useEffect(() => {
    console.log("---------")
    console.log("useEffect() is called");
    console.log(`isFull: ${isFull}`);
  });
  
  useEffect(() => {
    setIsFull(cout >= MAX_CAPACITY);
    console.log(`Current count value: ${count}`);
  }, [count]);
  
  return (
    <div style={{ padding: 16 }}>
      <p>{`${count}명 수용했습니다.`}</p>
      
      <button onClick={increaseCount} disabled={isFull}>
        입장
      </button>
      <button onClick={decreaseCount}>퇴장</button>
      
      {isFull && <p style={{ color: "red" }}> 정원이 가득찼습니다. </p>}
    </div>
  )
}

1개의 댓글

comment-user-thumbnail
2023년 4월 27일

There are school girls who offer types of assistance to clients and you will view as many close . They are carefree little kids and like to analyse. https://www.sanakhan.in/mumbai-call-girls.html You can invest some quality energy with them on the off chance that you need.

답글 달기