useContext (typescript) 정리

ryuyh2000·2022년 4월 1일
0

#React

목록 보기
3/4
post-thumbnail

useReducer에 이어 useContext도 공부를 했다.

useContext를 말로 설명하자니 쫌 어려울 것 같다. 그림으로 설명하겠다.

그림과 같이 lev.1에 lev.2 가 상속되어있고 lev.2에 lev.3이 되어있다. lev.1에 있는 props를 lev.3에 보내야 하는데 useContext를 사용하지 않게 보내게 되면그림의 왼쪽 부분처럼 lev.2를 거쳐 lev.3으로 가야한다. 이를 'Props Drilling' 이라한다.

Props Drilling:

Props Drilling은 코딩에 있어 치명적인 오류를 발생시키진 않는다.
하지만 넘겨야할 props가 10,15개 이상 넘어가게 되었을때 해당 props를 추적하기하기에 힘들고, 유지보수하기 또한 힘들다.

위와 같은 이유로 이를 방지하기 위해 useContext를 사용한다. 사용방법은 이렇다.

기본꼴은 이렇다.

import React, { createContext } from "react";

export const ThemContext = createContext("초기값");

Context를 우선 만들어준후 초기값을 지정해준후 export 해준다.

import React from "react";
import UseContext from "./UseContext/UseContext";
import { ThemContext, basicData } from "./UseContext/Context";
const App=()=>{
	return(
      	<ThemContext.Provider
        	value={{ boolean: basicData.boolean, name: basicData.name }}
      	>
        	<UseContext />
      	</ThemContext.Provider>
	)}

<export한함수.Provider value={}></export한함수.Provider>로 상위 컴포넌트를 감싸준다.

이렇게 하면 하위 컴포넌트에 const { 변수 } = React.useContext(ThemContext); 이런식을 사용가능핟.

밑은 저번에 공부했던 useReducer를 곁들여 useContext를 사용해본 코드다.

//Context.tsx

import React, { createContext } from "react";

export const basicData ={
  boolean:true,
  name:'찬호'
}

export const ThemContext = createContext(basicData);
//App.tsx

import React from "react";
import UseContext from "./UseContext/UseContext";
import { ThemContext, basicData } from "./UseContext/Context";

const App = () => {
  return (
    <>
    <ThemContext.Provider
        value={{ boolean: false, name: '인욱' }}
      >
        <UseContext />
      </ThemContext.Provider>
    </>
  );
};

export default App;
//UseContext.tsx

import React from "react";
import UseContextApplication from "./UseContextApplication";

const UseContext = () => {
  return (
    <>
      <UseContextApplication />
    </>
  );
};

export default UseContext;
//UseContextApplication.tsx

import React from "react";
import { ThemContext } from "./Context";

const reducer = (state: string, action: string): string => {
  if (action === "찬호") {
    state = "찬호";
    return state;
  } else {
    state = "인욱";
    return state;
  }
};

const UseContextApplication = () => {
  const { boolean, name } = React.useContext(ThemContext);
  const [boo, setBoo] = React.useState(boolean);
  const [sdaf, dispatch] = React.useReducer(reducer, name);

  return (
    <>
      <button
        onClick={() => {
          setBoo(!boo);
          if (boo) {
            dispatch("인욱");
          } else {
            dispatch("찬호");
          }
        }}
      >
        change info
      </button>
      {String(boo)}
      {sdaf}
    </>
  );
};

export default UseContextApplication;

블로그 글을 적으면서 느끼는거지만 진짜 설명을 너무 못한다. 다시보면 나조차 이해 못 할 것 같다. 아마 설명을 이렇게 못하는 이유는 이해를 완전히 못 했기 때문이 아닐까 싶다...

3줄 요약

  1. 상위에서 하위로 포롭스를 보낼때 다이랙트로 보내기 위해
  2. props drilling 은 좋지 않다.
  3. 진짜 설명 못한다. 멀미날 정도다.

git)https://github.com/ryuyh2000/react-Hook-prac!

profile
응애 프론트앤드 개발자

0개의 댓글

관련 채용 정보