npm install @reduxjs/toolkit react-redux
import { configureStore } from "@reduxjs/toolkit";
export const store = configureStore({
reducer: {},
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import type { RootState, AppDispatch } from "./store";
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
"use client";
import React from "react";
import { Provider } from "react-redux";
import { store } from "./store";
type Children = {
children: React.ReactNode;
};
export default function Providers({ children }: Children) {
return (
<>
<Provider store={store}>{children}</Provider>
</>
);
}
use client 를 사용해서 layout.tsx 에서도 불러올수 있도록 한다.
<body suppressHydrationWarning={true}>
<script
dangerouslySetInnerHTML={{
__html: themeInitializerScript,
}}
></script>
// 감싸주기
<Providers>
<Card>
<Header />
<ContentCard>{children}</ContentCard>
<Foorter />
<div id="portal"></div>
</Card>
</Providers>
</body>
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
bpm: 60,
};
export const bpmSlice = createSlice({
name: "bpm",
initialState,
reducers: {
changeBpm: (state, action) => {
state.bpm = action.payload;
},
},
});
export const { changeBpm } = bpmSlice.actions;
import { configureStore } from "@reduxjs/toolkit";
import { bpmSlice } from "./features/bpmSlice";
export const store = configureStore({
reducer: {
bpm: bpmSlice.reducer,
},
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
import { useDispatch, useSelector } from "react-redux";
import { changeBpm } from "@/redux/features/bpmSlice";
import { RootState } from "@/redux/store";
...
const dispatch = useDispatch();
const bpmFromRedux = useSelector((state: RootState) => state.bpm.bpm);
GOOD 👍