Last active
April 29, 2022 07:20
-
-
Save bfollington/cd4c0a6e7fd255f9def1eb75aaa64c15 to your computer and use it in GitHub Desktop.
useReducer + @reduxjs/toolkit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useReducer } from "react"; | |
import { messages, initialMessagesState } from "./slices/messages"; | |
const App: React.FC = () => { | |
const [messageList, dispatch] = useReducer( | |
messages.reducer, | |
initialMessagesState | |
); | |
return ( | |
<div className="App"> | |
<header className="App-header"> | |
<button onClick={() => dispatch(messages.actions.addMessage("Test"))}> | |
Hey | |
</button> | |
{messageList.map(m => ( | |
<li key={m}>{m}</li> | |
))} | |
</header> | |
</div> | |
); | |
}; | |
export default App; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createSlice } from "@reduxjs/toolkit"; | |
export const initialMessagesState: string[] = []; | |
export const messages = createSlice({ | |
name: "messages", | |
initialState: initialMessagesState, | |
reducers: { | |
addMessage(draft, action: { payload: string }) { | |
draft.push(action.payload); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the improvement @Kepro, I've updated the code to match yours, the
immer
API is cleaner here.For anyone who finds this gist on google, there's no good reason why the solution here reduxjs/redux-toolkit#484 requires a ref. We're just taking advantage of the
@reduxjs/toolkit
API for declaring a reducer concisely and passing a pure function touseReducer
.