Next.js) Redux Toolkit 세팅을 해보자..

준영·2023년 5월 3일
1

Redux Toolkit이란

설치

npm install @reduxjs/toolkit react-redux

Redux Toolkit은 리덕스의 사용성을 개선하고 코드를 간결하게 작성할 수 있게 해주는 라이브러리이다.

초기세팅

store.ts

import { configureStore } from '@reduxjs/toolkit';
import exampleSlice from './exampleSlice';

export const store = configureStore({
    reducer: {
        // slice
        example: exampleSlice,
    },
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

app.tsx

import type { AppProps } from 'next/app';
import { Provider } from 'react-redux'; // redux
import { store } from '@/store/store';

export default function App({ Component, pageProps }: AppProps) {
    return (
        <Provider store={store}>
            <Component {...pageProps} />
        </Provider>
    );
}

exampleSlice.ts

import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';

export interface exampleState {
    value: number;
}

const initialState: exampleState = {
    value: 0,
};

export const exampleSlice = createSlice({
    name: 'example',
    initialState,
    reducers: {
        increment: (state) => {
            // Redux Toolkit allows us to write "mutating" logic in reducers. It
            // doesn't actually mutate the state because it uses the Immer library,
            // which detects changes to a "draft state" and produces a brand new
            // immutable state based off those changes
            state.value += 1;
        },
        decrement: (state) => {
            state.value -= 1;
        },
        incrementByAmount: (state, action: PayloadAction<number>) => {
            state.value += action.payload;
        },
    },
});

// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = exampleSlice.actions;

export default exampleSlice.reducer;

사용해보기

index.js

import { decrement, increment } from '@/store/exampleSlice';
import { RootState } from '@/store/store';
import Head from 'next/head';
import { useDispatch, useSelector } from 'react-redux';

export default function Home() {
    const reduxTest = useSelector((state: RootState) => state.example.value);
    const dispatch = useDispatch();

    return (
        <>
            <Head>
                <title>Boilerplate</title>
                <meta
                    name="description"
                    content="Generated by create boilerplate"
                />
                <meta
                    name="viewport"
                    content="width=device-width, initial-scale=1"
                />
                <link rel="icon" href="/favicon.ico" />
            </Head>
            <div>hello world! {reduxTest}</div>
            <button
                onClick={() => {
                    dispatch(increment());
                }}
            >
                +
            </button>
            <button
                onClick={() => {
                    dispatch(decrement());
                }}
            >
                -
            </button>
        </>
    );
}

출력화면

profile
개인 이력, 포폴 관리 및 기술 블로그 사이트 👉 https://aimzero-web.vercel.app/

0개의 댓글