react context 예시

해적왕·2022년 7월 1일
0

context는 일일이 props를 넘겨주지 않고도 컴포턴트 전체에 데이터를 제공 할 수 있게 한다.
일일이 넘겨주면 되잖아? 라고 과거에 생각했었지만 components가 늘어날 수록 하나의 데이터를 props로 연결하려고 보니 정말 고역이었다. 그럴 때 사용하는 것이다.

예 )

const example = ({ data }) => {
	return(
    	<div>
        {data.map(...)}
        </div>
    )}

이런 식으로 부모로 받아오던 데이터를

import { exampleContext } from './context'
const example = () => {
const { data } = exampleContext();
	return(
    	<div>
        {data}
        </div>
    )
}

이렇게 바로 불러 올 수 있게 한다.

Context.js
기본 양식이다. 처음 볼 때는 너무 복잡해 보여 막연하게 어렵게만 생각했는데 그냥 기본 으로 들어가는 코드라고 보면 된다. currentUser를 불러 올 수 있다.

import { createContext, useContext, useEffect, useState } from 'react';

const UseExample = createContext();
export const exampleContext = () => useContext(useExample);

export const exampleContextProvider = ({ children }) => {
	const [ currentUser, setCurrentUser ] = useState(1);
    
    const value = {
    	currentUser,
    }
    return <UseExample.Provider value={value}> { children } </UseExample.Provider >
}

index.js
전역에서 사용할 수 있게 <App /> 감싸주어야 한다.

import { exampleContextProvider } from './Context.js';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <exampleContextProvider>
    <App/>
    </exampleContextProvider>
  </React.StrictMode>
);

example.js
currentUser를 불러올 곳이다.

import { exampleContext } from './Context.js';

const example = () => {
	const { currentUser } = exampleContext();
	return(
    	<div>
        	{currentUser}
        </div>
    )
}

적용법이 내 기준 복잡하다. 여러 번 써봤음에도 불구하고 처음 적용할 때는 했던 걸 보면서 치게 된다.. 능숙해 질 수 있게 context 관련으로 글을 써야겠다.

profile
프론트엔드

0개의 댓글