Skip to content

Instantly share code, notes, and snippets.

@revskill10
Forked from aweary/App.js
Created October 25, 2018 18:31
Show Gist options
  • Select an option

  • Save revskill10/8d20b65cda7b033d880c8114978707c1 to your computer and use it in GitHub Desktop.

Select an option

Save revskill10/8d20b65cda7b033d880c8114978707c1 to your computer and use it in GitHub Desktop.

Revisions

  1. @aweary aweary revised this gist Oct 25, 2018. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions useMutableReducer.js
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,5 @@
    import {useReducer, useCallback} from 'react';
    import {produce} from 'immer';

    function useMutableReducer(reducer, initialState, initialAction) {
    const mutableReducer = useCallback(
  2. @aweary aweary created this gist Oct 24, 2018.
    23 changes: 23 additions & 0 deletions App.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    import React from "react";
    import useMutableReducer from "./useMutableReducer";

    const reducer = (draft, action, state) => {
    switch (action) {
    case "increment":
    draft.count++;
    break;
    case "decrement":
    draft.count--;
    }
    };

    const App = () => {
    const [state, dispatch] = useMutableReducer(reducer, { count: 0 });
    return (
    <>
    <h1>{state.count}</h1>
    <button onClick={() => dispatch("increment")}>+</button>
    <button onClick={() => dispatch("decrement")}>-</button>
    </>
    );
    };
    13 changes: 13 additions & 0 deletions useMutableReducer.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    import {useReducer, useCallback} from 'react';

    function useMutableReducer(reducer, initialState, initialAction) {
    const mutableReducer = useCallback(
    (state, action) => {
    return produce(draft => {
    return reducer(draft, action, state);
    });
    },
    [reducer]
    );
    return useReducer(mutableReducer, initialState, initialAction);
    }