개발/react

useContext

kwony 2020. 12. 22. 21:09

useContext를 사용하면 하위 컴포넌트에서도 상위 컴포넌트에서 전달하는 값을 공유 받을 수 있다. props를 통해서 전달하지 않고 동일한 Context를 넘겨 받은 인자를 통해서 공유가 가능하다. 이 함수를 이용해 state 값과 이를 업데이트 하는 dispatch 함수를 컴포넌트끼리 공유 할 수 있다.

 

1. Context 만들기 

 

하위 컴포넌트에서 공통적으로 공유할 수 있는 React Context를 만든다.

 

import React from 'react';

const NotesContext = React.createContext()

export { NotesContext as default }

 

2. Context 공유하기 

 

공유를 시작하려는 가장 상위 컴포넌트에서 태그를 씌워준다. value 안에 넣어둔 값들은 하위 컴포넌트에서 접근 할 수 있게 된다.

 

const NoteApp = () => {
  
    const [notes, dispatch] = useReducer(notesReducer, [])
  
    ...
  
    return (
      <NotesContext.Provider value={{ notes, dispatch }}>
        <h1>Notes</h1>
        <NoteList />
        <p>Add note</p>
        <AddNoteForm />
      </NotesContext.Provider>

 

3. 공유 데이터 접근 

 

하위 컴포넌트에서는 useContext 함수와 공통적으로 사용하고 있는 Context를 이용해 공유 데이터에 접근 할 수 있다. 아래 코드를 보면 useContext를 이용해 상위에서 공유하는 notes 인자를 접근하고 jsx로 만드는 형태다.

 

import React, { useContext } from 'react';
import Note from './Note';
import NotesContext from '../context/notes-context';

const NoteList = () => {
    const { notes } = useContext(NotesContext)

    return notes.map((note) => (
        <Note key={note.title} note={note} />
      ))
}

export { NoteList as default }