๐ด Introduction
โช ์๋ฐ์คํฌ๋ฆฝํธ ์ํ๊ด๋ฆฌ ๋ผ์ด๋ธ๋ฌ๋ฆฌ
๐ Official
Redux ์์ํ๊ธฐ | Redux
์๊ฐ > ์์ํ๊ธฐ: Redux๋ฅผ ๋ฐฐ์ฐ๊ณ ์ฌ์ฉํ๊ธฐ ์ํ ์๋ฃ
ko.redux.js.org
๐ก Install

npm i redux react-redux
npm i @reduxjs/toolkit
npm i redux-logger
npm i redux-thunk
๐ข Usage

// [ index.jsx ]
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { Provider } from "react-redux";
import store from "./store/store";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<>
<Provider store={store}>
<App />
</Provider>
</>
);

// [ store.js ]
import { configureStore } from "@reduxjs/toolkit";
import logger from "redux-logger";
import ReduxThunk from "redux-thunk";
import pageReducer from "./slices/pageSlice";
const store = configureStore({
reducer: {
page: pageReducer,
},
middleware: (getDefaultMiddleware) => [
...getDefaultMiddleware({ serializableCheck: false }),
logger,
ReduxThunk,
],
});
export default store;

// [ pageSlice.js ]
import { createSlice } from "@reduxjs/toolkit";
export const PageSlice = createSlice({
name: "page",
initialState: {
currentPage: "1",
},
reducers: {
setCurrentPage: (state, { payload }) => {
state.currentPage = payload;
},
},
});
// redux-thunk function usage
export const checkValid =
({ keys, onSuccess = (f) => f, onFail = (f) => f }) =>
(dispatch, getState) => {
// dispatch ์ด์ ์ ๋จผ์ ์ฒ๋ฆฌํ ๋น์ฆ๋์ค ๋ก์ง ๊ตฌํ
if (keys) return onSuccess();
return onFail();
};
export const { setCurrentPage } = PageSlice.actions;
export default PageSlice.reducer;

// [ Usage Component ]
import { useSelector, useDispatch } from "react-redux";
import { setCurrentPage } from "../../store/slices/pageSlice";
const Component = () => {
// set redux state
const dispatch = useDispatch();
const setPage = dispatch(setCurrentPage((prev) => prev + 1));
// get redux state
const curPage = useSelector((state) => state.page.currentPage);
// usage of redux-thunk
dispatch(checkValid({ option });
}
'React > Library' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ React ] react-hook-form (0) | 2022.08.04 |
---|---|
[ React ] classnames (0) | 2022.08.04 |
[ React ] react-router-dom (0) | 2022.07.31 |
[ React ] react-helmet (0) | 2022.07.30 |
[ React ] recoil (0) | 2022.07.30 |