boiler plate
import React from 'react';
import { Provider } from 'react-redux';
import store from './store/store';
export default function App() {
return (
<Provider store={store}>
<Home/>
</Provider>
);
}
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterReducer';
export default configureStore({
reducer: {
counter: counterReducer,
},
});
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
count: 0,
};
export const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
setCounter: (state, action) => {
state.count = action.payload;
},
},
extraReducers: {},
});
export const { setCounter } = counterSlice.actions;
export const selectCounter = (state) => state.counter.count;
export default counterSlice.reducer;
1. 예시는 counter 예시로 한다.
2. useSelector, useDispatch
selectCounter, setCounter에 대해 알아보자.
setCounter
는 setState처럼 setter의 역할을 한다.
...
const dispatch=useDispatch();
dispatch(setCounter(1));
selectCounter는 store의 state를 참조한다.
...
const count=useSelector(selectCounter);
console.log(count);
...