• useEffect
    • 새로운 데이터가 들어올 때마다, 변화가 일어날 때 컴포넌트를(ui를) 새로고침함
    • 그르나 어떤 코드들은 계속 계속 실행하면 안될 수도 있음 
    • 그렇기 때문에 useEffect를 통해서 우리가 원할 때에 새로고침을 할 수 있음
    • 함수의 인자는 실행하려는 코드, 지켜보려는 것으로만 이루어져 있음  
useEffect(() => {
    console.log("나는 한번만 실행돼용");
  }, []); //처음 실행시에 딱 한번만 실행되고 다시는 하지마라
  useEffect(() => {
      console.log("나는 키워드가 변화할 때 실행됨요");
  }, [keyword]); //시작할 때랑 keyword가 변화할 때 코드를 실행하고 싶다면
  useEffect(() => {
      console.log("나는 카운터가 변화할 때 실행됨요");
  }, [counter]); //시작할 때랑 counter가 변화할 때 코드를 실행하고 싶다면
  useEffect(()=>{
    console.log("나는 카운터랑 키워드가 변화할때 실행됨요")
  }, [keyword,counter]);//시작할 때랑 counter나 keyword가 변화할 때 코드를 실행하고 싶다면

'React' 카테고리의 다른 글

#7.0 To Do List part One  (1) 2023.03.10
#6.4 Cleanup  (0) 2023.03.10
#6.2 Deps  (0) 2023.03.10
#6.1 useEffect  (0) 2023.03.10
#6.0 Introduction  (0) 2023.03.10
  • 글자를 타핑할때마다 api를 새로 호출한하고 가정하면 -> 겁나 별로
  • search keyword에 변화가 있을때만 검색하고 싶음
  • counter가 변화할 때에도 영화를 검색하고 싶지 않음
  • 코드의 특정한 부분만이 변화했을 때 원하는 코드들을 실행할 수 있게 하고싶음
import { useEffect, useState } from "react";

function App() {
  const [counter, setValue] = useState(0);
  const [keyword, setKeyword] = useState("")
  const onClick = () => setValue((prev) => prev + 1);
  const onChange = (event) => setKeyword(event.target.value); //event를 발생시킨 input에서 value를 받아서 keyword에 넣음
  
  useEffect(() => {
    console.log("나는 한번만 실행돼용");
  }, []); //아무것도 변화하지 않았을 때 코드를 실행(리액트가 지켜볼것이 없음)
  useEffect(() => {
      console.log("나는 키워드가 변화할 때 실행됨요");
  }, [keyword]); //keyword가 변화할 때 코드를 실행하고 싶다면
  useEffect(() => {
      console.log("나는 카운터가 변화할 때 실행됨요");
  }, [counter]); 
  useEffect(()=>{
    console.log("나는 카운터랑 키워드가 변화할때 실행됨요")
  }, [keyword,counter]);
  return (
    <div>
      <input value={keyword} onChange={onChange} type="text" placeholder="Search here..." />
      <h1>{counter}</h1>
      <button onClick={onClick}>click me</button>
    </div>
  );
}

export default App;

'React' 카테고리의 다른 글

#6.4 Cleanup  (0) 2023.03.10
#6.3 Recap  (1) 2023.03.10
#6.1 useEffect  (0) 2023.03.10
#6.0 Introduction  (0) 2023.03.10
#5.1 Tour of CRA  (1) 2023.03.08
  • useEffect
    • 두개의 인자를(arguent)가지는 함수
    • 첫번째 인자:우리가 딱 한번만 실행하고 싶은 코드(api를 딱 한번만 호출하고 싶을 때 등)
    • 두번째 인자: 리액트가 지켜봐야 할 것, 이것이 변화할 때 리액트가 코드를 실행시킴 
import { useEffect, useState } from "react";

function App() {
  const [counter, setValue] = useState(0);
  const onClick = () => setValue((prev)=> prev+1);
  console.log("항상 실행됨");
  useEffect(()=>{
    console.log("CALL THE API..");
  },[]);
  return (
    <div>
      <h1>{counter}</h1>
      <button onClick={onClick}>click me</button>
    </div> 
  );
}

export default App;

'React' 카테고리의 다른 글

#6.3 Recap  (1) 2023.03.10
#6.2 Deps  (0) 2023.03.10
#6.0 Introduction  (0) 2023.03.10
#5.1 Tour of CRA  (1) 2023.03.08
#5.0 Introduction  (2) 2023.03.08
  • state가 변화할 때 항상 모든 component는 다시 실행되고, 모든 code들도 다시 실행됨
  • component내부의 몇몇 코드는 처음만 실행되고 다시는 실행되지 않도록 하고 싶다 -> effect
import { render } from "@testing-library/react";
import { useState } from "react";

function App() {
  const [counter, setValue] = useState(0);
  const onClick = () => setValue((prev)=> prev+1);
  console.log("render"); //state가 변경될 때마다 (버튼을 클릭할때마다) 계속 rander됨
  return (
    <div>
      <h1>{counter}</h1>
      <button onClick={onClick}>click me</button>
    </div> 
  );
}

export default App;

'React' 카테고리의 다른 글

#6.2 Deps  (0) 2023.03.10
#6.1 useEffect  (0) 2023.03.10
#5.1 Tour of CRA  (1) 2023.03.08
#5.0 Introduction  (2) 2023.03.08
#4.2 Prop Types  (1) 2023.03.08
  • css 코드를 자바스크립트 객체로 변환시켜줌
    import styles from "./~";

  • styles가 css 코드를 가지고 있는 객체로 넘어옴
    따라서 해당 css코드에 작성된 class name(여기서는 btn)을 프로퍼티 접근 연산자(.)를 사용해서 이용가능해짐.

    < Button style={styles.btn} / >
    위와 같이 작성해서 해당 css 스타일링을 사용할 수 있음.

  • 브라우저를 통해 html 코드를 확인해보면 해당 컴포넌트에 무작위의 class name이 붙음.
    요소가 각각의 클래스네임을 가지게 돼서 일일이 class name을 기억해서 스타일링 할 필요가 없음
.btn {
    color: white;
    background-color: tomato;
}
.title {
    font-family: 'Courier New', Courier, monospace;
    font-size: 18px;
}
import PropTypes from "prop-types";
import styles from "./Button.module.css"; //css코드를 자바스크립트 오브젝트로 변환,style를 모듈러로 만들 수 있다

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

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

export default Button;
import Button from "./Button";
import styles from "./App.module.css";

function App() {
  return (
   <div>
    <h1 className={styles.title}>Welcome back!</h1>
    <Button text={"Continue"}/>
   </div>
  );
}

export default App;

'React' 카테고리의 다른 글

#6.1 useEffect  (0) 2023.03.10
#6.0 Introduction  (0) 2023.03.10
#5.0 Introduction  (2) 2023.03.08
#4.2 Prop Types  (1) 2023.03.08
#4.1 Memo  (2) 2023.03.08
  • 라액트 프로젝트 만드는 법

  • 프로젝트 깔끔하게 정리해주기 

function App() {
  return (
   <div>
    <h1>Welcome back!</h1>
   </div>
  );
}

export default App;

app.js

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

index.js

'React' 카테고리의 다른 글

#6.0 Introduction  (0) 2023.03.10
#5.1 Tour of CRA  (1) 2023.03.08
#4.2 Prop Types  (1) 2023.03.08
#4.1 Memo  (2) 2023.03.08
#4.0 Props  (1) 2023.03.08

1.리액트는 파라미터를 잘 못 넘겨도 확인할 수 없는 문제점이 존재한다.
2. 이런 문제를 줄이기 위해서 PropTypes라는 모듈의 도움을 받을 수 있다.
3. type과 다르게 입력 돼었을 경우 warning을 뜨게 할수 있고, parameter 에 값을 넣지 않는 경우 경고 메시지를 띄울수 있다.

<!DOCTYPE html>
<html>

<body>
    <div id="root"></div>
</body>
<script src="https://unpkg.com/react@17.0.2/umd/react.development.js "></script>
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>
<script type="text/babel">
    function Btn({text, fontSize = 16}) {
        return (
        <button
            style={{
                backgroundColor: "tomato",
                color: "white",
                padding: "10px 20px",
                border: 0,
                borderRadius: 10,
                fontSize: fontSize,
            }}
        >
         {text}
        </button>
        );
    }
    Btn.propTypes = { //타입지정
        text: PropTypes.string.isRequierd,
        fontSize: PropTypes.number,
    }
    function App() {
        return (
            <div>
                <Btn text="Save Change" fontSize={18}/>
                <Btn />
            </div>
        );
    }
    const root = document.getElementById("root");
    ReactDOM.render(<App />, root);
</script>

</html>

'React' 카테고리의 다른 글

#5.1 Tour of CRA  (1) 2023.03.08
#5.0 Introduction  (2) 2023.03.08
#4.1 Memo  (2) 2023.03.08
#4.0 Props  (1) 2023.03.08
#3.9 Final Practice and Recap  (2) 2023.03.07
    • text, onClick은 단지 props의 이름임
<div>
                <Btn text={value} onClick={changeValue} />
                <Btn text="Continue" />
            </div>
  • state가 변경될 때마다  rerender가 발생함
  • props가 변경되지 않는다면 컴포넌트를 다시 그릴지 말지를 결정할 수 있음 -> MemorizedBtn = React.memo(Btn)
  • 불필요한 re-render는 React.memo()로 관리할 수 있음
    부모 컴포넌트의 state를 변경하면 당연히 그 자식 컴포넌트들도 Re-render가 일어남. 불필요한 렌더링이 발생할 수도 있는데, 이 경우에는 React.memo()로 prop의 변경이 일어난 부분만 렌더링 시킬 수 있음. 아주 많은 자식 컴포넌트를 가지고 있는 부모 컴포넌트일 때 사용하면 됨
  • React.memo()
    컴포넌트가 React.memo()로 wrapping 될 때, React는 컴포넌트를 렌더링하고 결과를 메모이징(Memoizing)한다. 그리고 다음 렌더링이 일어날 때 props가 같다면, React는 메모이징(Memoizing)된 내용을 재사용한다.
<!DOCTYPE html>
<html>

<body>
    <div id="root"></div>
</body>
<script src="https://unpkg.com/react@17.0.2/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
    function Btn({text, changeValue}) {
        console.log(text, "was rendered");
        return (
            <button
            onClick={changeValue}
            style={{
                backgroundColor: "tomato",
                color: "white",
                padding: "10px 20px",
                border: 0,
                borderRadius: 10,
                fontSize: 10,
            }}
        >
         {text}
        </button>
        );
    }
    const MemorizedBtn = React.memo(Btn)
    function App() {
        const [value, setValue] = React.useState("Save Changes")
        const changeValue = () => setValue("Revert Changes");
        return (
            <div>
                <MemorizedBtn text={value} changeValue={changeValue} />
                <MemorizedBtn text="Continue" />
            </div>
        );
    }
    const root = document.getElementById("root");
    ReactDOM.render(<App />, root);
</script>

</html>

'React' 카테고리의 다른 글

#5.0 Introduction  (2) 2023.03.08
#4.2 Prop Types  (1) 2023.03.08
#4.0 Props  (1) 2023.03.08
#3.9 Final Practice and Recap  (2) 2023.03.07
#3.8 Recap  (1) 2023.03.07

+ Recent posts