Hooks & Context

woom·2023년 6월 29일
0

React

목록 보기
9/9
post-thumbnail

출처 : 패스트캠퍼스 한 번에 끝내는 프론트엔드 개발 초격차 패키지


📕 Basic Hooks

  • 클래스에서만 가능했던 state를 함수안에서 사용 가능

    • state와 관련된 로직을 재사용 가능
  • 종류

    • useState : state를 대체 가능
    • useEffect : 라이프 사이클 훅을 대체 가능(componentDidMount, componentDidUpdate, componentWillUnmount)
    • useContext(Context API에서 다룸)

🐣 useState

import React from "react";

//useState => {count : 0};
export default function Example2() {
  const [state, setState] = React.useState({ count: 0 });

  return (
    <div>
      <p>You clicked {state.count} times</p>
      <button onClick={click}>Click me</button>
    </div>
  );

  function click() {
    setState((state) => ({
      count: state.count + 1,
    }));
  }
}

🐣 useEffect

  • 첫번째 렌더링 : 컴포넌트야 state가 0일 때의 UI를 보여줘
  • jsx전달(return) 후 useeffect함수 실행하는 거 있지말라고 전달
  • 브라우저야 UI업데이트 해줘
import React from "react";

export default function Example5() {
  const [count, setCount] = React.useState(0);

  React.useEffect(() => {
    console.log("componentDidMount");
    return () => {};
    //cleanup(다음 실행 직전에 return후 console창 출력)
    //빈배열로 작성시 : 항상 render가 된 직후에 실행해라
  }, []);

  React.useEffect(() => {
    console.log("componentDidMount & componentDidUpdate by count", count);

    return () => {
      //cleanup(count값 변경 되기 전의 값이 출력됨)
      console.log("cleanup by count", count);
    };
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={click}>Click me</button>
    </div>
  );

  function click() {
    setCount(count + 1);
  }
}

📙 Custom Hooks

import { useState, useEffect } from "react";

export default function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const resize = () => {
      setWidth(window.innerWidth);
    };

    window.addEventListener("resize", () => resize);

    return () => {
      window.removeEventListener("resize", resize);
    };
  }, []);
  return width;
}

useHasMounted vs withHasMounted

profile
Study Log 📂

0개의 댓글

Powered by GraphCDN, the GraphQL CDN