REACT ⑤ Basic Hooks

옛슬·2021년 12월 30일
0

REACT 🔵

목록 보기
5/16
post-thumbnail

🚩 해당 글은 유튜브 The Net Ninja와 React 공식문서를
공부한 토대로 작성된 글입니다. 혹시라도 잘못된 글이 있다면
댓글로 알려주세요 🏃‍♀️🏃‍♀️ + 해당 글은 배울때마다 추가됩니다.

■ Basic Hooks

- useState

기본 문법

const [state, setState] = useState(initialState);
setState(newState);
  • state는 상태를 뜻한다. 즉 상태가 변화하는 값, 혹은 함수가 업데이트될 때 사용
  • 처음 렌더링 될 때 state의 값은 initialState에 적은 값이다.
  • setState()함수는 상태를 업데이트할 때 쓰인다. 렌더링이 다시될 때 해당 함수 값으로 업데이트 된다.
  • 만약에 setState()함수에서 이전 값을 사용할 때는 함수를 만들어 사용하면 이전 값을 사용할 수 있다.
function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
    </>
  );
}

- useEffect

  • componentDidMount, componentDidUpdate, componentWillUpdate 조합의 형태로 기능동작을 한다고 할 수 있다.

기본 문법

useEffect(didUpdate);
  • 기본동작 : 모든 렌더링을 완료한 후 effect를 발생하게 된다.
  • 렌더링 될 때마다 실행됨.

Conditionally firing an effect

useEffect(
  () => {
    const subscription = props.source.subscribe();
    return () => {
      subscription.unsubscribe();
    };
  },
  [props.source],
);
  • [ 두번째 값 ]은 useEffect의 dependency인데 해당 dependency가 업데이트 될 때마다 useEffect가 실행됨.
  • deps라고 많이 부르고 [ 배열 ] 형태이다.
  • 빈 배열인 경우 컴포넌트가 마운트 될 때만 실행된다.
useEffect(
  ()=>{
  console.log('마운트+btn업데이트 마다 실행~!');
  },
  [btn]
)
  • deps에 검사하고 싶은 값을 넣으면 마운트될 때, 그 다음 deps가 업데이트 될때 실행된다.
useEffect(
  ()=>{
  	console.log('마운트+btn업데이트 마다 실행~!');
 	return ()=>{
      console.log('cleanup 함수 실행!');
   }
  },[btn])'
  • return문 뒤에 나오는 함수는 cleanup 함수라고 한다.
  • (1) deps에 빈배열 인 경우 언마운트 될 때만 실행됨.
  • (2) deps안에 값을 넣는 경우 해당 값이 업데이트 되기 직전에 cleanup함수는 실행된다.

★ useEffect 정리

(1) Mount

  • deps가 빈 배열일 때 : 최초 렌더링 시 한번 만 실행된다
    useEffect(effect,[])

(2) Update

  • 렌더링 될 때마다 실행 : deps가 없는 경우
    useEffect(effect)
  • 특정 deps가 업데이트시에만 실행 : deps 배열에 넣어줌
    useEffect(effect, [deps1, deps2, ... ])

    여기에서 dependencies란?
    it must include all values that are used inside the callback and participate in the React data flow. That includes props, state, and anything derived from them.

(3) Unmount

  • return 문 뒤에 나오는 함수 (cleanup함수)를 활용
  • 언마운트 될 때 실행 (한번): deps가 빈 배열인 경우
  • 업데이트 되기 직전에 실행 : deps에 값이 있는 경우, 즉 다음의 effect를 적용하기 전에 이전에 effect는 정리한다고 생각하면 된다.
    effect실행 → 해당effect정리 → 다음effect 실행 → 해당effect정리
import React, { useState, useEffect } from 'react';

function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    // Specify how to clean up after this effect:
    return function cleanup() {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}

Fetching data in react using hooks
리액트 공식문서 - Using the effect hook

- useContext

  • 기존에는 최상위 컴포넌트에서 여러 레벨을 거쳐 props로 상태와 함수를 전달함.
  • useContext를 통해 한번에 전달할 수 있음.
const themes = {
  light: {
    foreground: "#000000",
    background: "#eeeeee"
  },
  dark: {
    foreground: "#ffffff",
    background: "#222222"
  }
};

// 1️⃣ 부모에서 받을 prop을 React.createContext()에 담는다.
// createContext() 함수는 Provider와 Consumer를 반환한다.
const ThemeContext = React.createContext(themes.light);

function App() {
  return (
    // 2️⃣ 사용할 부분을 <이름.Provider>로 묶는다.
    // value값을 하위 컴포넌트에 전달하게 된다.
    <ThemeContext.Provider value={themes.dark}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

function ThemedButton() {
  // 3️⃣ 기본문법 const value = useContext(받아올컨텍스트변수)
  const theme = useContext(ThemeContext);
  return (
    <button style={{ background: theme.background, color: theme.foreground }}> // 4️⃣ 받아온 background, foreground 사용할 수 있음.
      I am styled by theme context!
    </button>
  );
}

■ Additional Hooks

👉 사용별로 사용하게 될 때 공부 후 입력 예정 😉

- useReducer

- useMemo

- useCallback

- useRef

- useImperativeHandle

- useLayoutEffect

- useDebugValue

profile
웹 퍼블리셔입니다💓

0개의 댓글