REACT_NEXT.JS에서 redux를 사용해보자.

JSkim·2022년 6월 14일
0

어쩌다보니 next.js 로 프로젝트를 하나 만들게 되었다.(테스트 용으로 살짝 찍먹정도...)

next.js를 사용하는 이유는 서버사이드 렌더링으로 인한 이득을 보기위해서 라고하는데

자세한 내용은

구글에 CSR SSR 검색 해보십쇼..

SEO(검색최적화) 할때 좋다고 하고, 또 하면서 느낀건 react-router-dom 안써도 됨.
자체적으로 라우터기능을 지원한다.

암튼 프로젝트 생성하고

리덕스 설치 하자.

npm install next-redux-wrapper react-redux @reduxjs/toolkit

이렇게 설치 해주자. 로그 보려면 redux-logger 도 설치 ㄱㄱ

그리고 최상위 폴더에 이렇게 있을텐데 여기 store 폴더 하나 만들고
store폴더 안에 modules폴더도 하나 만들어주자.

ProjectName
ㄴ.next
ㄴnode_modules
ㄴpages
ㄴstyles
ㄴstore <--새로 만든 폴더

이제 리덕스 세팅 ㄱㄱ

store/index.js

store폴더 안에 index.js 라는 파일 하나만들고 다음과 같이 작성한다. 스토어 작성

import { configureStore } from '@reduxjs/toolkit';
import { createWrapper } from "next-redux-wrapper";
import logger from 'redux-logger'; //로그볼라고

import reducer from './modules';

const makeStore = (context) => configureStore({
    reducer,
    middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger),
    devTools: process.env.NODE_ENV !== 'production',
});

export const wrapper = createWrapper(makeStore, {
    debug: process.env.NODE_ENV !== 'production',
});

store/modules/index.js

modules폴더 안에도 index.js를 하나 작성해보자. 리듀서 작성.

import {combineReducers} from "redux";
import {HYDRATE} from "next-redux-wrapper";

import test from './test';

const reducer =(state,action)=> {
    if (action.type === HYDRATE) {
        return {
            ...state,
            ...action.payload
        };
    }
    return combineReducers({
        test
    })(state,action)
}
export default reducer;

저 test라는 리듀서는 modules 폴더 안에 넣었다.

store/modules/test.js



const TEST = 'TEST'


export const testAction =(body)=>{
    console.log(body)
    return{
        type:TEST,
        payload: body
    }
};


const initialState ={아무거나:''};

const test = (state=initialState,action)=>{
    switch (action.type){
        case TEST:
            return {...state,아무거나:action.payload }
        default:
            return state
    }
}

export default test

여기는 뭐 기존 redux 쓰던것 처럼 하면 됩니다...

이렇게 세팅하면 기존 쓰던것 처럼
디스패치하고 셀렉터하고 사용해서 슥삭 쓰면 됩니다.

profile
제주도 프론트앤드 개발자의 개발 일기

0개의 댓글