useContext

김듑듑·2022년 8월 31일
0

프론트엔드

목록 보기
9/24

https://ko.reactjs.org/docs/hooks-reference.html#usecontext
https://ko.reactjs.org/docs/context.html

props를 글로벌하게 사용할 수 있게 도와주는거


ex
a>b>c 끼리 부모자식관계이고
a->c로 props를 전달하려고 함
그럼 기존에는 a->b->c 순으로 props를 전달해야했음 아님 전역으로 상태관리를 하던가


이 문제를 해결하는게 useContext

-useContext는 context를 읽고 context의 변경을 구독하는 것만 가능
-useContext로 전달한 인자는 context 객체 그 자체
-context를 사용하면 컴포넌트 재사용하기 어려움
-상위 컴포넌트에서 React.memo를 사용하더라도 useContext를 사용하고 있는 컴포넌트 자체에서부터 리렌더링됨 -> 메모이제이션 사용해서 최적화 필요


여전히 a>b>c 라고 치고

ex1. 객체 전달
출처(https://velog.io/@jminkyoung/TIL-6-React-Hooks-useContext-%EB%9E%80)

export const 어쩌고저쩌고 = createContext();

const A = () => {
  const 객체 = {
    name: "이름",
    age: "나이"
  };

  return (
  	<어쩌고저쩌고.Provider value={객체}>
    	<B />
    </AppContext.Provider>
  );
};
import { 어쩌고저쩌고 } from "./A";

const B = () => {
  return (
      <어쩌고저쩌고.Consumer>
        {(객체) => (
        	<p>{객체.name}, {객체.age}</p>
        )}
      </어쩌고저쩌고.Consumer>
  );
};

아니면

const B = () => {
  const 객체 = useContext(어쩌고저쩌고);
  return (
    <p>{객체.name}, {객체.age}</p>
  );
};

ex2. 메서드 전달
출처(https://www.zerocho.com/category/React/post/5fa63fc6301d080004c4e32b)

export const 어쩌고저쩌고 = createContext({
  setLoggedIn: () => {},
  setLoading: () => {},
});

export const A = () => {
  const [loggedIn, setLoggedIn] = useState(false);
  const [loading, setLoading] = useState(false);
  
  const value = useMemo(() => (
  	{ setLoggedIn, setLoading }), [setLoggedIn, setLoading]);
    
  return (
    <어쩌고저쩌고.Provider value={value}>
      <B />
    </UserContext.Provider>
  );
};
export const B = () => {
  return <C />;
};
import { 어쩌고저쩌고 } from './A';

export const C = () => {
  const { setLoading, setLoggedIn } = useContext(UserContext);
 
  return (
    <>
      <button onClick={() => setLoading((prev) => !prev)}>로딩토글</button>
      <button onClick={() => setLoggedIn((prev) => !prev)}>로딩토글</button>
    </>
  );
};

0개의 댓글