• Feed
  • Explore
  • Ranking
/
/
    React

    React Hook - useContext

    ReactuseContextcreateContextProvider
    전
    전상욱
    2025.04.10
    ·
    2 min read

    useContext()란?

    해당 Hook을 사용하면 함수형 컴포넌트에서 Context를 보다 더 쉽게 사용할 수 있다.

    App.js

    import React, { useState, createContext } from 'react';
    import exampleContext from './exampleContext.jsx';
    
    export const colorContext = createContext();
    
    const App = () => {
      const [color, setColor] = useState('red');
    
      return (
        <colorContext.Provider value={ color }>
        	<exampleContext />
        </colorContext.Provider>
      )
    }
    
    export default App;

    exampleContext.jsx

    import React, { useContext } from 'react';
    import { colorContext } from './App';
    
    const exampleContext = () => {
      const theme = useContext(colorContext);
      return (
        <div>{ theme }</div>;  // App.js로부터 받은 Context 사용 가능
      )
    }
    
    export default exampleContext;

    마무리

    1. 하위 컴포넌트로 전달해줄 값을 상위 컴포넌트에서 createContext로 생성 후 export 한다.
    2. 전달 받을 하위 컴포넌트를 <Context명.Provider>를 사용하여 묵어준다.
    3. Context로 전달해줄 값을 <Context명.Provider value={값}> 넣어준다.
    4. 전달 받을 하위 컴포넌트에서 Context를 import하고 그 값을 useContext인자로 넣어준다.
    5. useContext에서 return된 값을 하위 컴포넌트에서도 사용할 수 있다.







    - 컬렉션 아티클