[NextJS] NextJS에 Mobx 세팅하기

NextJS에 Mobx 세팅하기

[목표]



왜 Mobx를 사용 하는가?



1. Mobx 설치하기

[mobx-react]

 npm install mobx-react --save

 //or

 yarn add mobx mobx-react

[babel] : 데코레이터 사용을 위한 babel설치

npm install @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators


//or

yarn add @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators


2. .babelrc 생성


// .babalrc

{
    "presets": ["next/babel"],
    "plugins": [
        [
            "@babel/plugin-proposal-decorators",
            {
                "legacy": true
            }
        ],
        [
            "@babel/plugin-proposal-class-properties",
            {
                "loose": true
            }
        ]
    ]
}


3. _app.js에 mobx Provider 세팅해주기



///_app.js

import { Provider } from "mobx-react";
import { useStore } from "../stores/Store";

function MyApp({ Component, pageProps }) {
    const store = useStore(pageProps);
    return (
        <div className="page__wrap">
                <Provider store={store}>
                    <Component {...pageProps} />
                </Provider>
            </div>

        </div>
    );
}


// /stores/Store.js

import { action, observable, makeObservable } from "mobx";
import { enableStaticRendering, MobXProviderContext } from "mobx-react";
import { useMemo, useContext } from "react";

import CartStore from "./CartStore";
import UserStore from "./UserStore";

// eslint-disable-next-line react-hooks/rules-of-hooks
enableStaticRendering(typeof window === "undefined");

let store = null;

const isServer = typeof window === "undefined";

class Store {
    cartStore = new CartStore();
    userStore = new UserStore();

    constructor(props) {
        makeObservable(this);
        this.hydrate(props);
    }

    @action
    hydrate = data => {
        if (data) {
            this.userStore = new UserStore(data);
        }
    };
}

function initializeStore(initialData) {
    // if _store is null or undifined return new Store
    //otherwise use _store

    // If your page has Next.js data fetching methods that use a Mobx store, it will
    // get hydrated here, check `pages/ssg.js` and `pages/ssr.js` for more details


    // For SSG and SSR always create a new store
    if (isServer) {
        return {
            cartStore: new CartStore(),
            userStore: new UserStore(initialData),
        };
    }

    // Create the store once in the client
    if (store === null) {
        store = {
            cartStore: new CartStore(),
            userStore: new UserStore(initialData),
        };
    }

    return store;
}

export function useStore(initialState) {
    const store = useMemo(() => initializeStore(initialState), [initialState]);
    return store;
}



[참고 문서]