Next.js에서 React hook의 Context를 사용하는 방법

Kyle_Kim·2023년 8월 1일
0

필요한 Library들

import React, { createContext, useContext, useReducer } from 'react';
import { todoReducer } from './TodoReducer'; // Import the todoReducer 

dispatcher에서 필요한 Action정의

type TodoAction = { type: 'CREATE'; data: Todo };

dispatcher에 필요되는 parameter값들 정의.

interface TodoContextValue {
  tasks: Todo[];
  dispatch: React.Dispatch<TodoAction>;
  onCreate: (content: Todo) => void;
}

- tasks: Todo리스트를 구성하는 entity. 리스트로 정의되어 있다.

- dispatch: 리액트 Hook의 useReducer로 만들어진 함수

- onCreate : A function that takes a Todo item as an argument and is used to add a new Todo item to the list.

위에 정의한 TodoContextValue interface를 기반으로 한 Context를 생성.

export const TodoContext = createContext<TodoContextValue>({
  tasks: [],
  dispatch: () => {},
  onCreate: () => {},
});

- default값이 정의된 함수들.

- 리스트일 경우 비어져 있는 리스트, 함수는 비워져 있는 함수.

커스텀 훅을 생성후 export한다.

export const useTodoContext = () => useContext(TodoContext);
profile
Make Things Right

1개의 댓글

comment-user-thumbnail
2023년 8월 1일

유익한 글이었습니다.

답글 달기