0.9.0 • Published 1 year ago

use-immer v0.9.0

Weekly downloads
37,503
License
MIT
Repository
github
Last release
1 year ago

use-immer

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

Installation

npm install immer 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 or a value as argument.

Managing state with immer producer function

When passing a function to the updater, the draft argument can be mutated freely, until the producer ends 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)

Managing state as simple useState hook

When passing a value to the updater instead of a function, useImmer hook behaves the same as useState hook and updates the state with that value.

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

function BirthDayCelebrator(){
  const [age, setAge] = useImmer(20);

  function birthDay(event){
    setAge(age + 1);
    alert(`Happy birthday #${age} Anon! hope you good`);
  }

  return(
    <div>
      <button onClick={birthDay}>It is my birthday</button>
    </div>
  );
}

Obviously if you have to deal with immutability it is better option passing a function to the updater instead of a direct value.

useImmerReducer

Immer powered reducer, based on useReducer hook

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

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

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>
    </>
  );
}
@lwtears/admin-common@tokdaniel/superfluid-widget@hilma/formsbootflex2react-use-huskyreact-use-mahozaro-webocr-front@apraamcos/apra-amcos-uicra-template-notum-material-uireact-bootstrap-extensionsreact-bootstrap-extensionapra-amcos-uilewis-todo-coponents@doublethinkio/spoon@lanaco/lanaco-react-libraryjlmc@heights/heights-uiedisen-ui@infinitebrahmanuniverse/nolb-use-i@a1740942002/widgetcontainer-data-analyticscompanyon-form-builder@pixiebrix/extensionjgu-zac-appsfo-test2react-tagilize@everything-registry/sub-chunk-3026companyon-formbuilder@voytenkodev/pagination-react-ts@novin/salerator-componentsye-designweb-builder-toolwhistle.modifywebpack5-appwjtkzc-first-todolist@groupos/smart-accounts@wechange/frontend-core@salerator.net/components@walterguo/widget1@utahdts/utah-design-systemeva-requestevaporator-common@vrabbi/plugin-scaffolder-react@wz-ditg/hooks@wz-ditg/taroexpo-template-bare-tsexpo-template-ts@worldprinter/components@worktools/meson-form@worktools/rough-table@web3-systems/react-multichainemoji-jsqeli-conversation-intervieweli-video-intervieweli-video-interview-demo@superfluid-finance/widget@telus/koodo-global-elements@tntd/decision-tree-diagram@tntx/decision-tree-diagram@tomazjejcic/contentfultree@shuyun-ep-team/kylin-ui-plus@sim-design/analysis-report@sim-design/case-analysis@sim-design/data-selector@sim-design/form@sim-design/pro-paper@sim-design/questionnaire@sim-design/simddutchskull-scene-managerdutchskull-svg-editor@visual-interface/engine@visual-interface/page-base@ttungbmt/react-hooks@ttungbmt/redux-starter-kitelewis-ui-common@tugraph/openpiece-clientdrip-form-theme-react-vantfe-pre-view@alkuip/jsonforms@alkuip/tablesfugitnulla@antv/gi-sdk@antv/gi-assets-advance@antv/gi-assets-algorithm@antv/gi-assets-basic@antv/gi-assets-galaxybase@antv/gi-assets-graphscope@antv/gi-assets-gs@antv/gi-assets-hugegraph@antv/gi-assets-neo4j@antv/gi-assets-tugraph@antv/gi-assets-xlab@antv/gi-common-components@antscorp/form-design@antribute/uiagenda-rcfriday-immerfull-form
0.9.0

1 year ago

0.8.1

1 year ago

0.8.0

1 year ago

0.7.0

2 years ago

0.6.0

3 years ago

0.5.2

3 years ago

0.5.0

3 years ago

0.5.1

3 years ago

0.4.2

3 years ago

0.4.1

4 years ago

0.4.0

4 years ago

0.3.5

4 years ago

0.3.4

5 years ago

0.3.3

5 years ago

0.3.2

5 years ago

0.3.1

5 years ago

0.3.0

5 years ago

0.2.2

5 years ago

0.2.1

5 years ago

0.2.0

5 years ago

0.1.0

5 years ago

0.0.5

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago