Skip to content

Instantly share code, notes, and snippets.

@bfollington
Last active April 29, 2022 07:20
Show Gist options
  • Save bfollington/cd4c0a6e7fd255f9def1eb75aaa64c15 to your computer and use it in GitHub Desktop.
Save bfollington/cd4c0a6e7fd255f9def1eb75aaa64c15 to your computer and use it in GitHub Desktop.
useReducer + @reduxjs/toolkit
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;
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);
}
}
});
@OnurGvnc
Copy link

@Kepro
Copy link

Kepro commented Jun 17, 2021

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);
    }
  }
});

@bfollington
Copy link
Author

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 to useReducer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment