LoginSignup
0
0

More than 1 year has passed since last update.

next.jsでreactのcreateContextをviewとデータを切り離して綺麗に書く方法

Posted at

開発環境:
macOSX catalina バージョン10.15.7
visualStudioCode
react
next.js

createContextを綺麗に書く方法を教わったので、備忘録

以下のような書き方をして、Contextを定義する
そうすることによって、viewとデータを切り離すことができ、可読性が高まるとのこと

import React, { useReducer, createContext } from "react";
import reducer from "./reducer";

const tagList = [];

const MyContext = createContext("");
const Store = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, tagList);
  return (
    <MyContext.Provider value={{ state, dispatch }}>
      {children}
    </MyContext.Provider>
  );
};

export { MyContext, Store };

以下のようにContextを下位コンポーネントにつなぐ

import "../styles/globals.css";
import React from "react";
import { Store } from "../store/store";

function MyApp({ Component, pageProps }) {
  return (
    <Store>
      <Component {...pageProps} />
    </Store>
  );
}

export default MyApp;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0