[공부로그] 리액트 3주차

가비·2022년 8월 3일

공부로그

목록 보기
6/14

5. Create React App

  • App.js에서 버튼을 import할 수 있게 함
export default Button;
  • import 해서 사용하기
import Button from "./Button";
  • style 적용할 때 세가지 방법이 있다. 첫번째는 전체 css 파일을 만드는 것이고 하나는 style prop을 이용하는 것이고 마지막은 module.css를 사용하는 것이다.
button {
    color: white;
    background-color: tomato;
}

전체가 import 되어서 변수가 많아지면 곤란하다.

<button style={{
    backgroundColor: "tomato",
    color: "white",
}}></button>

버튼마다 일일이 지정해줘야한다,,,

  1. Button.module.css
.btn {
    color: white;
    background-color: tomato;
}

Button.js

import PropTypes from "prop-types";
import styles from "./Button.module.css";

function Button({text}) {
    return (
        <button className={styles.btn}>
            {text}
        </button>
    )
}

Button.propTypes = {
    text: PropTypes.string.isRequired,
}

export default Button;

랜덤하게 클래스 명을 지정해준다.

6. Effect

우리는 전체 코드를 리랜더링해왔다. 그러나 api를 호출한다거나 할때는 그 코드를 반복실행하지 않아야 한다.

  • useEffect 함수를 통해 처음 한 번만 실행될 코드를 지정할 수 있다.
console.log("i run all the time"); //항상 실행

useEffect(() => {
  console.log("I run only once.");
}, []); //처음에만 실행

useEffect(() => {
  console.log("I run when 'keyword' changes.");
}, [keyword]); //keyword가 변화할 때 실행


useEffect(() => {
  if (keyword !== "" && keyword.length > 5) {
    console.log("Search For", keyword);
  }
}, [keyword]); //특정 조건에서 실행

useEffect(() => {
  console.log("I run when 'counter' changes.");
}, [counter]); //counter가 변화할 때 실행

useEffect(() => {
  console.log("I run when 'keyword & counter' changes.");
}, [keyword, counter]); //keyword나 counter가 변할 때 실행
  • cleanUp function
    component가 destroy될 때 띄워줌
useEffect(() => {
  console.log("created :)");
  return () => console.log("destroyed :(");
}, []);

create 될 때 destroy함수도 불러오는 원리이다.

profile
개발데분꿈나무🌳

0개의 댓글