본문 바로가기

TIL/기록

[TIL] Context API

 

1. Context 생성 

const LetterContext = createContext();

 

 

 

 

2. Provider 제공

 

import { createContext } from 'react';

function Provider컴포넌트() {
	const userName = "Kim";
	const age = 25;

	return {
		<LetterContext.Provider value={{ 
			userName, 
			age, 
		}}>
			<spelling />
		</LetterContext.Provider>  
   };
}

 

 

 

3. Consumer 사용

 

import React, { useContext } from "react";

function Consumer컴포넌트() {
	const data = useContext(LetterContext);
    
	return (
            <div>
                내 이름은 <span>{data.userName}</span>입니다.
           	내 나이는 <span>{data.age}</span>입니다. 
            </div>
    )
}

export default Consumer컴포넌트;

 

 

여기서의 {data.userName}은 props가 아니다.

 

useContext를 사용할때는 Provider에서 제공한 value가 달라진다면 useContext를 사용하고 있는 모든 컴포넌트가 리렌더링 된다.

따라서 value 부분을 항상 신경써줘야한다.

그걸 보완할 수 있는것이 메모이제이션이다.

 

현재 프로젝트중에 context를 해야할것이 있어 정리해보았다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'TIL > 기록' 카테고리의 다른 글

[TIL] redux 문제  (1) 2024.02.08
[TIL] Tab 활성화  (0) 2024.02.05
[TIL] Redux란?  (1) 2024.02.01
[TIL] useState와 useRef  (0) 2024.01.31
[TIL] hook - useContext  (1) 2024.01.30