React Context

✒️ 2025-05-28 10:39 내용 수정


React Component 트리 안에서 전역적이라 볼 수 있는 데이터를 공유하기 위한 방법

import { createContext } from "react";

function App() {
	// Context 생성하기
	const CustomContext = createContext(defaultValue); // defaultValue : 트리 내에 적절한 Provider가 없을 때 사용

	return (
		// Provider로 Context를 사용할 Component의 범위를 지정할 수 있음
		<CustomContext.Provider value={/*사용할 값*/}>
			{/* Context를 사용할 Component를 추가 */}
			<Test></Test>
		</CustomContext.Provider>
	)
}
import { createContext } from "react";

const CustomContext = createContext();

export default CustomContext;
import { useState, useContext } from 'react';
import CustomContext from '../contexts/CustomContext';

function App() {
	return (
		const [custom, setCustom] = useState('test');
		{/* custom을 Test에서도 사용할 수 있다. */}
		<CustomContext.Provider value={custom}>
			{/* Context를 사용할 Component를 추가 */}
			<Test></Test>
		</CustomContext.Provider>
	)
}
import { useState, useContext } from 'react';
import CustomContext from '../contexts/CustomContext';

function Test() {
	{/* Provider로부터 받은 Context 가져와서 변수에 저장 */}
	const contextValue = useContext(CustomContext);
	
	return(
		<span>{contextValue}</span>
	)
}

Context를 개별 함수로 관리하기

// TestContext.js
import React, { createContext, useContext, useState } from "react";

const TestContext = createContext();

export function useTest() {
    return useContext(TestContext);
}

export function TestProvider({ children }) {
    const [testValue, setTestValue] = useState('');

    return (
        <TestContext.Provider value={{ testValue, setTestValue }}>
            {children}
        </TestContext.Provider>
    );
}

export default TestContext;
// App.js
import { TestProvider } from "./TestContext.js";
import ChildComponent from "./ChildComponent.js";

function App() {
    return (
        <TestProvider>
            <ChildComponent />
        </TestProvider>
    );
}

export default App;
// ChildComponent.js
import { useTest } from "./TestContext.js";

function ChildComponent() {
	// Context로 전달한 value를 꺼내올 수 있다.
	const {testValue, setTestValue} = useTest();

    return (
		<></>
    );
}

export default ChildComponent;