Redux toolkit 을 React에 적용하기 ep.2 (counter 예제)

YANGHYUK·2021년 4월 2일
0

CRA(create-react-app) +Typescript 위에서 redux-toolkit 공식문서에 있는 간단한 카운터를 따라해보자

//src/index.js
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import store from './app/store'
import { Provider } from 'react-redux'

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)
//src/store
import { configureStore } from '@reduxjs/toolkit';
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import countSlice from 'src/store/counter/counterSlice';
const store = configureStore({
  reducer: { counter: countSlice },
});

export default store;

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
//src/store/counter/counterSlice
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { RootState, useAppSelector, useAppDispatch } from 'src/store';

interface CounterState {
  value: number;
}

// Define the initial state using that type
const initialState: CounterState = {
  value: 0,
};

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => {
      state.value = state.value + 1;
    },
    decrement: (state) => {
      state.value = state.value - 1;
    },
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value = state.value + action.payload;
    },
  },
});

export const { increment, decrement, incrementByAmount } = counterSlice.actions;

export function HooksCounter() {
  const count = useAppSelector((state: RootState) => state.counter.value);
  const dispatch = useAppDispatch();

  return {
    count,
    dispatch,
  };
}

export default counterSlice.reducer;
//src/components/Counter/CounterComponent
import React from 'react';
import { decrement, increment, HooksCounter } from 'src/store/counter/counterSlice';
export default function CounterComponent() {
  const { count, dispatch } = HooksCounter();
  return (
    <div>
      <button aria-label="Increment value" onClick={() => dispatch(increment())}>
        Increment
      </button>
      <span>{count}</span>
      <button aria-label="Decrement value" onClick={() => dispatch(decrement())}>
        Decrement
      </button>
    </div>
  );
}

profile
code runner

0개의 댓글