React

230615 CountApp 만들기

hyerin1201 2023. 6. 15. 14:02

useEffect( ) : 어떤값이 변경될때 마다 특정코드를 실행시켜주는 함수

useEffect( callback, [ ] ) : 2번째 인자값으로 들어온 배열객체가 변경될때 마다 콜백함수 실행

비동기방식의 복수의 이벤트가 중복되었을때 이벤트 종료시점으로 동기처리하고 다시 새롭게 시작하도록 해주는 기능

[ ] 에 값을 할당하지 않은경우 컴포넌트 변경에 따라서 callback함수가 작동한다.

-> useEffect( ) 의 클린업 기능

 

END단락 평가 (&&) : 조건문 && 컴퍼넌트 실행 -> 참이면 컴퍼넌트 실행, 거짓이면 실행하지 않음

import React, { useEffect, useState } from "react";
import logo from "./logo.svg";
import "./App.css";
import Viewer from "./Component/Viewer";
import Controller from "./Component/Controller";
import Even from "./Component/Even";

function App() {
  const [count, setCount] = useState(0);
  const [text, setText] = useState("");
  const handleSetCount = (value: number) => {
    setCount(count + value);
  };
  const handleChangeText = (e: React.ChangeEvent<HTMLInputElement>) => {
    setText(e.target.value);
  };

  useEffect(() => {
    console.log("count 업데이트: ", text, count);
  }, [text, count]);

  useEffect(() => {
    const pointCount = setInterval(() => {
      console.log("포인트");
    }, 1000);

    return () => {
      console.log("클린업");
      clearInterval(pointCount);
    };
  });
  return (
    <div className="App">
      <h1>Simple Counter</h1>
      <section>
        <input type="text" value={text} onChange={handleChangeText} />
      </section>
      <section>
        <Viewer count={count} />
        {count % 2 === 0 && <Even />}
      </section>
      <section>
        <Controller handleSetCount={handleSetCount} />
      </section>
    </div>
  );
}

export default App;

Viewer.tsx

interface numOne {
  count: number;
}

const Viewer = ({ count }: numOne) => {
  return (
    <div>
      <div>현재카운트: </div>
      <h1>{count}</h1>
    </div>
  );
};

export default Viewer;

Controller.tsx

interface numTwo {
  handleSetCount: any;
}

const Controller = ({ handleSetCount }: numTwo) => {
  return (
    <div>
      <button onClick={() => handleSetCount(-1)}>-1</button>
      <button onClick={() => handleSetCount(-10)}>-10</button>
      <button onClick={() => handleSetCount(-100)}>-100</button>
      <button onClick={() => handleSetCount(+100)}>+100</button>
      <button onClick={() => handleSetCount(+10)}>+10</button>
      <button onClick={() => handleSetCount(+1)}>+1</button>
    </div>
  );
};

export default Controller;

Even.tsx

import { useEffect } from "react";

function Even() {
  useEffect(() => {
    return () => {
      console.log("Even 컴퍼넌트");
    };
  }, []);
  return <div>현재카운트는 짝수입니다.</div>;
}

export default Even;