useEffect(), 관련퀴즈

Juyeon Lee·2022년 5월 19일
0

REACT 리액트

목록 보기
36/65

api처럼 리액트 외부에 있는걸 쓸 때 쓰는 hook이 useEffect이다.
Effect Hook lets you perform side effects in function components
Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects.

useEffect()쓰는 법

import React from "react"

export default function App() {
    const [starWarsData, setStarWarsData] = React.useState({})
    const [count, setCount] = React.useState(0)
    
    console.log("Component rendered")
    
    /**
     * Challenge: re-write the useEffect
     * It should run any time `count` changes
     * For now, just console.log("Effect function ran")
     */
    React.useEffect(() => {
        console.log("Effect function ran")
    }, [count])
    
    return (
        <div>
            <pre>{JSON.stringify(starWarsData, null, 2)}</pre>
            <h2>The count is {count}</h2>
            <button onClick={() => setCount(prevCount => prevCount + 1)}>Add</button>
        </div>
    )
}


  React.useEffect(() => {
        console.log("Effect function ran")
    }, [count])

바로 이 부분이다. 분명히 로직 다 이해하고 혼자 할 때 이렇게 썼는데
왜 난 오류가 났던거지... 음?

  1. What is a "side effect" in React? What are some examples?
    - Any code that affects an outside system.
    - local storage, API, websockets, two states to keep in sync
  1. What is NOT a "side effect" in React? Examples?
    - Anything that React is in charge of.
    - Maintaining state, keeping the UI in sync with the data,
    render DOM elements
  1. When does React run your useEffect function? When does it NOT run
    the effect function?
    - As soon as the component loads (first render)
    - On every re-render of the component (assuming no dependencies array)
    - Will NOT run the effect when the values of the dependencies in the
    array stay the same between renders
  1. How would you explain what the "dependecies array" is?
    - Second paramter to the useEffect function
    - A way for React to know whether it should re-run the effect function
   React.useEffect(function() {
        console.log("Effect ran")
        // fetch("https://swapi.dev/api/people/1")
        //     .then(res => res.json())
        //     .then(data => console.log(data))
    }, [])
    

이 코드에서 보면 두번째 parmeter가 있잖아? 이게 dependencies array라는거다.. 이거의 역할은 첫번째 콜백함수에 있는 애들을 얼마만큼이나
진행하게 할건지 정해주는 거다... 저렇게 [ ] 적어주면 딱 한번만 rendering한다. 왜냐면 저기 안에 trigger해서 다시 돌려주라는 애들이 없는 빈 array이기 때문이다.

예를 들어서 이렇게 코드가 되어있다면

 React.useEffect(function() {
        fetch("https://swapi.dev/api/people/1")
            .then(res => res.json())
            .then(data => console.log(data))
    }, [count])

count가 늘어날때마다 fetch 코드가 작동되는거임ㅎㅎ

밑의 코드도 살펴보자

import React from "react"

export default function App() {
    const [starWarsData, setStarWarsData] = React.useState({})
    const [count, setCount] = React.useState(1)
    
    React.useEffect(function() {
        console.log("Effect ran")
        fetch(`https://swapi.dev/api/people/${count}`)
            .then(res => res.json())
            .then(data => setStarWarsData(data))
    }, [count])
    
    return (
        <div>
            <h2>The count is {count}</h2>
            <button onClick={() => setCount(prevCount => prevCount + 1)}>Get Next Character</button>
            <pre>{JSON.stringify(starWarsData, null, 2)}</pre>
        </div>
    )
}

api 끝의 숫자가 달라져야 다른 array element가 나오니까
저렇게 해주고 dendencies array도 count로 설정해줬다.
count가 달라질때마다 다시 rendering 되야하니까

0개의 댓글