首页 > 其他分享 >use-immer

use-immer

时间:2023-09-25 15:44:55浏览次数:36  
标签:function use immer useImmer state draft

use-immer

TypeScript icon, indicating that this package has built-in type declarations 0.9.0 • Public • Published 6 months 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>
    </>
  );
}

Keywords

标签:function,use,immer,useImmer,state,draft
From: https://www.cnblogs.com/sexintercourse/p/17728057.html

相关文章

  • immerjs:React开发必会技能
    immerjs:React开发必会技能龙骑士尹道长 ​关注 2人赞同了该文章我们都知道React追求的泛式是数据不可变,一般情况下state或者props改变才进入render阶段;如果我们创建的state是一个一般数据类型,他就是一个不可变的值,如果需要改变我们需要重新创建一个state......
  • OGG MA - Not Able To Log InAdmin server ERROR: User name 'oggadmin' or password
    ogg的密码文件可能会损坏需要修复就新建一个新的ogg微服务并且把密码文件考到问问题的地方进行覆盖,我觉得这个是一个bugTherecommendationistoCreateadummyMAinstallationonthesameserverordifferenttestserver.Thencopythewallet[cwallet.sso]fromthis......
  • 1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains n
    博客园首页新随笔联系管理订阅随笔-111 文章-1 评论-3 阅读-17万 1055-Expression#1ofORDERBYclauseisnotinGROUPBYclauseandcontainsnonaggregatedcolumn'information_schema.PROFILING.SEQ'whichisnotfunctionally......
  • Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregate
    MySQL有any_value(field)函数,他主要的作用就是抑制ONLY_FULL_GROUP_BY值被拒绝官方有介绍,地址:https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value我们可以把select语句中查询的属性(除聚合函数所需的参数外),全部放入any_value(field)函数......
  • UserWarning: The parameter 'pretrained' is deprecated since 0.13 and may be remo
    从torchvision0.13开始,加载预训练模型函数的参数从pretrained=True改为weights=预训练模型参数版本。且旧版本的写法将在未来的torchvision0.15版本中被Deprecated。fromtorchvisionimportmodels#旧版本的写法,将在未来的torchvision0.15版本中被Deprecatedmod......
  • es 编写查询DSL,查询user_name字段不为空的文档
    内容来自对chatgpt的咨询我们可以使用exists查询来检查user_name字段是否存在且包含非空值:{"query":{"bool":{"must":{"exists":{"field":"user_name"......
  • ClickHouse的数据表设计与性能优化最佳实践探究
    前言ClickHouse是一个高性能的列式数据库,它的设计目标是处理大规模数据集的复杂分析查询。在使用ClickHouse时,数据表的设计和性能优化是非常重要的。本文将深入探讨ClickHouse的数据表设计与性能优化最佳实践。数据表设计列的选择在设计数据表时,需要根据实际情况选择合适的列。......
  • ClickHouse的分布式查询优化
    介绍ClickHouse是一个高性能的列式存储数据库,支持分布式部署。在分布式环境下,如何优化查询性能是一个非常重要的问题。本文将深入探讨ClickHouse的分布式查询优化。分布式查询的挑战在分布式环境下,查询性能的瓶颈通常是网络带宽和节点之间的通信延迟。因此,优化分布式查询的关键......
  • ClickHouse数据表合并与性能优化方法探讨与案例研究分享
    前言ClickHouse是一款高性能的列式数据库,其在海量数据处理方面具有很强的优势。但是,在实际应用中,我们经常需要对多个数据表进行合并,以便更好地进行数据分析和挖掘。本文将探讨ClickHouse的数据表合并与性能优化方法,并结合实际案例进行分享。数据表合并在ClickHouse中,数据表合并......
  • Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connect
    报错 Maxretriesexceededwithurl:/(CausedbyNewConnectionError('<urllib3.connection.HTTPSConnectionobjectat0x000001A73833FD00>:Failedtoestablishanewconnection:[WinError10060]  pipuninstallrequestsurllib3  #先卸载pipinstallre......