46

GitHub - mweststrate/use-immer: Use immer to drive state with a React hooks

 5 years ago
source link: https://github.com/mweststrate/use-immer
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

README.md

use-immer

A hook to use immer as a React hook to manipulate state.

Warning: Hooks are currently a React RFC and not ready for production. Use at minimum [email protected] to use this package.

Installation

npm install use-immer

API

useImmer

useImmer(initialState) is very similar to useState. The function returns a tuple, the first value of the tuple is the current state, the second is the updater function, which accepts an immer producer function, in which the draft can be mutated freely, until the producer ends and and the changes will be made immutable and become the next state.

Example: https://codesandbox.io/s/l97yrzw8ol

import React from "react";
import { useImmer } from "use-immer";


function App() {
  const [person, updatePerson] = useImmer({
    name: "Michel",
    age: 33
  });

  function updateName(name) {
    updatePerson(draft => {
      draft.name = name;
    });
  }

  function becomeOlder() {
    updatePerson(draft => {
      draft.age++;
    });
  }

  return (
    <div className="App">
      <h1>
        Hello {person.name} ({person.age})
      </h1>
      <input
        onChange={e => {
          updateName(e.target.value);
        }}
        value={person.name}
      />
      <br />
      <button onClick={becomeOlder}>Older</button>
    </div>
  );
}

(obviously, immer is a little overkill for this example)

useImmerReducer

Immer powered reducer, based on useReducer hook

Example: https://codesandbox.io/s/2zor1monvp

const initialState = { count: 0 };

function reducer(draft, action) {
  switch (action.type) {
    case "reset":
      return initialState;
    case "increment":
      return void draft.count++;
    case "decrement":
      return void draft.count--;
  }
}

function Counter() {
  const [state, dispatch] = useImmerReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "reset" })}>Reset</button>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
    </>
  );
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK