본문 바로가기

CS Study/React

5. Effects

이제는 create-react-app을 사용한다.

 

#index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

 

 

#useEffect 사용

 

경우에 따라 호출되는 함수를 지정할 수 있다!

아래 코드의 경우, runOnce라는 함수가

다른 컴포넌트이 변화와 상관없이

한 번만 호출됨(dependency가 없기 때문)

import {useState, useEffect} from "react";
function App() {
  const [counter, setValue] = useState(0);//state가 변경될 때 마다 re-render
  const onClick = () => setValue((prev)=>prev + 1);
  console.log("I run all time");
  const runOnce = () =>{//한번만 render될 함수
    console.log("I run once");
  }
  useEffect(runOnce,[]);
  return (
    <div>
      <h1>{counter}</h1>
      <button onClick = {onClick}>Click Me!</button>
    </div>
  );
}

export default App;

 

반면 아래 코드의 경우 useEffect함수의

dependency가 지정되어 있음.

 

dependency의 의미는

dependency에 해당하는 parameter의 변화가 있으면,

그 함수를 호출한다는 것이다.

 

아래 코드의 경우 key값이 변화하면,

I run when key changes / I run when key and counter change가 

console창에 출력되고,

 

counter값이 변화하면

I run when key and counter change만

console창에 출력된다.

 

그리고 이 App2가 렌더링될 때

I run once가 출력되고 더 이상 출력되지 않는다.

import {useState, useEffect} from "react";
function App2() {
  const [counter, setValue] = useState(0);
  const [key, setKeyvalue] = useState("");
  const onClick = () => setValue((prev)=>prev + 1);
  const onChange = (event) => setKeyvalue(event.target.value);
  useEffect(() =>{
      console.log("I run once");
  },[]);//한번만 render됨
  useEffect(()=> {
      console.log("I run when key changes");
  }, [key]);//[]안에 값이 변화할 때만 코드 실행 -> key가 변화할 때만 코드를 실행
  useEffect(() => {
      console.log("I run when key and counter change");
  },[key,counter]);//[]안에 값이 변화할 때만 코드 실행 -> key와 counter가 변화할 때 코드 실행
  return (
    <div>
      <input value ={key} onChange = {onChange} type = "text" placeholder="Search here..."/>
      <h1>{counter}</h1>
      <button onClick = {onClick}>Click Me!</button>
    </div>
  );
}

export default App2;

 

#Cleanup 함수

 

Hello 컴포넌트가 호출될 때(showing이 true일 때)

hiFn이 실행된다.

 

그리고,

Hello 컴포넌트가 사라질 때(showing이 false일 때)

byFn이 실행됨.

 

이러한 경우에, byFn을 Cleanup함수라고 한다!

import {useState, useEffect} from "react";

function Hello(){
    function byFn(){
        console.log("by :(");
    }
    function hiFn(){
        console.log("created :)");
        return byFn;//Hello 컴포넌트가 파괴될 때 return byFn -> cleanup Function
    }
    useEffect(hiFn,[])
    return (
        <h1>Hello</h1>
    )
}

function App3() {
  let [showing, setShowing] = useState(false);
  const onClick = () => setShowing(showing = !showing);
  return (
    <div>
      {showing ? <Hello /> : null}
      <button onClick = {onClick}>{showing ? "Hide" : "Show"}</button>
    </div>
  );
}

export default App3;

'CS Study > React' 카테고리의 다른 글

4. Props  (0) 2022.04.18
3. State  (0) 2022.04.16
2. JSX  (0) 2022.04.15
1. 왜 React 인가?  (0) 2022.04.15