Skip to content
Myr

index.html

This file

Path

_site/readme/index.html

1,190 lines · 37.6 KiB · HTML

Last changed by

Not known.

History of this file

Take it

1<img src="images/immer-logo.png" height="200px" align="right" />2<h1>Immer</h1>3<p>4	<a href="https://www.npmjs.com/package/immer"5		><img src="https://img.shields.io/npm/v/immer.svg" alt="npm"6	/></a>7	<a href="https://travis-ci.org/immerjs/immer"8		><img9			src="https://travis-ci.org/immerjs/immer.svg?branch=master"10			alt="Build Status"11	/></a>12	<a href="https://coveralls.io/github/immerjs/immer?branch=master"13		><img14			src="https://coveralls.io/repos/github/immerjs/immer/badge.svg?branch=master"15			alt="Coverage Status"16	/></a>17	<a href="https://bundlephobia.com/result?p=immer"18		><img19			src="https://img.shields.io/bundlephobia/minzip/immer.svg"20			alt="Minzipped size"21	/></a>22	<a href="https://github.com/prettier/prettier"23		><img24			src="https://img.shields.io/badge/code_style-prettier-ff69b4.svg"25			alt="code style: prettier"26	/></a>27	<a href="https://www.paypal.me/michelweststrate"28		><img29			src="https://img.shields.io/badge/Donate-PayPal-green.svg"30			alt="Donate"31	/></a>32</p>33<p>34	<em35		>Create the next immutable state tree by simply modifying the current36		tree</em37	>38</p>39<p>40	Winner of the &quot;Breakthrough of the year&quot;41	<a href="https://osawards.com/react/">React open source award</a> and42	&quot;Most impactful contribution&quot;43	<a href="https://osawards.com/javascript/">JavaScript open source award</a> in44	201945</p>46<h3><a href="https://github.com/immerjs/immer/releases">Release notes</a></h3>47<p>48	Did Immer make a difference to your project? Consider buying me a coffee!<br /><a49		href="https://www.buymeacoffee.com/mweststrate"50		target="_blank"51		><img52			src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png"53			alt="Buy Me A Coffee"54			style="height: auto !important;width: auto !important;"55	/></a>56</p>57<hr />58<ul>59	<li>NPM: <code>npm install immer</code></li>60	<li>Yarn: <code>yarn add immer</code></li>61	<li>62		CDN: Exposed global is <code>immer</code>63		<ul>64			<li>65				Unpkg:66				<code67					>&lt;script68					src=&quot;https://unpkg.com/immer/dist/immer.umd.js&quot;&gt;&lt;/script&gt;</code69				>70			</li>71			<li>72				JSDelivr:73				<code74					>&lt;script75					src=&quot;https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js&quot;&gt;&lt;/script&gt;</code76				>77			</li>78		</ul>79	</li>80</ul>81<hr />82<ul>83	<li>84		Egghead lesson covering all of immer (7m):85		<a86			href="https://egghead.io/lessons/redux-simplify-creating-immutable-data-trees-with-immer"87			>Simplify creating immutable data trees with Immer</a88		>89	</li>90	<li>91		Introduction blogpost:92		<a93			href="https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3"94			>Immer: Immutability the easy way</a95		>96	</li>97</ul>98<p>99	Immer (German for: always) is a tiny package that allows you to work with100	immutable state in a more convenient way. It is based on the101	<a href="https://en.wikipedia.org/wiki/Copy-on-write"102		><em>copy-on-write</em></a103	>104	mechanism.105</p>106<p>107	The basic idea is that you will apply all your changes to a temporary108	<em>draftState</em>, which is a proxy of the <em>currentState</em>. Once all109	your mutations are completed, Immer will produce the <em>nextState</em> based110	on the mutations to the draft state. This means that you can interact with111	your data by simply modifying it while keeping all the benefits of immutable112	data.113</p>114<p><img src="images/hd/immer.png" alt="immer-hd.png" /></p>115<p>116	Using Immer is like having a personal assistant; he takes a letter (the117	current state) and gives you a copy (draft) to jot changes onto. Once you are118	done, the assistant will take your draft and produce the real immutable, final119	letter for you (the next state).120</p>121<p>122	A mindful reader might notice that this is quite similar to123	<code>withMutations</code> of ImmutableJS. It is indeed, but generalized and124	applied to plain, native JavaScript data structures (arrays and objects)125	without further needing any library.126</p>127<h2>External resources</h2>128<ul>129	<li>130		Blog:131		<a132			href="https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/"133			>The Rise of Immer in React</a134		>135	</li>136	<li>137		Blog: by Workday Prism on why they picked Immer to manage immutable state138		<a139			href="https://medium.com/workday-engineering/workday-prism-analytics-the-search-for-a-strongly-typed-immutable-state-a09f6768b2b5"140			>The Search for a Strongly-Typed, Immutable State</a141		>142	</li>143	<li>144		Blog:145		<a href="https://daveceddia.com/react-redux-immutability-guide/"146			>Immutability in React and Redux: The Complete Guide</a147		>148	</li>149	<li>150		Video tutorial:151		<a152			href="https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState"153			>Using Immer with React.setState</a154		>155	</li>156	<li>157		<a href="https://www.youtube.com/watch?v=-gJbS7YjcSo">Talk</a> +158		<a href="http://immer.surge.sh/">slides</a> on Immer at React Finland 2018159		by Michel Weststrate160	</li>161	<li>162		<a href="https://www.youtube.com/watch?v=bFuRvcAEiHg&amp;feature=youtu.be"163			>ForwardJS 2019: Immutability is Changing - From Immutable.js to Immer</a164		>165		by <a href="https://twitter.com/swyx/">shawn swyx wang</a>166	</li>167</ul>168<h2>API</h2>169<p>The Immer package exposes a default function that does all the work.</p>170<p>171	<code172		>produce(currentState, producer: (draftState) =&gt; void): nextState</code173	>174</p>175<p>176	There is also a curried overload that is explained177	<a href="#currying">below</a>.178</p>179<h2>Example</h2>180<pre><code class="language-javascript">import produce from &quot;immer&quot;181182const baseState = [183	{184		todo: &quot;Learn typescript&quot;,185		done: true186	},187	{188		todo: &quot;Try immer&quot;,189		done: false190	}191]192193const nextState = produce(baseState, draftState =&gt; {194	draftState.push({todo: &quot;Tweet about it&quot;})195	draftState[1].done = true196})197</code></pre>198<p>199	The interesting thing about Immer is that the <code>baseState</code> will be200	untouched, but the <code>nextState</code> will reflect all changes made to201	<code>draftState</code>.202</p>203<pre><code class="language-javascript">// the new item is only added to the next state,204// base state is unmodified205expect(baseState.length).toBe(2)206expect(nextState.length).toBe(3)207208// same for the changed 'done' prop209expect(baseState[1].done).toBe(false)210expect(nextState[1].done).toBe(true)211212// unchanged data is structurally shared213expect(nextState[0]).toBe(baseState[0])214// changed data not (dûh)215expect(nextState[1]).not.toBe(baseState[1])216</code></pre>217<h2>Benefits</h2>218<ul>219	<li>220		Immutability with normal JavaScript objects and arrays. No new APIs to221		learn!222	</li>223	<li>Strongly typed, no string based paths selectors etc.</li>224	<li>Structural sharing out of the box</li>225	<li>Object freezing out of the box</li>226	<li>Deep updates are a breeze</li>227	<li>Boilerplate reduction. Less noise, more concise code.</li>228	<li>229		Small230		<a231			href="http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"232			><img233				src="http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js?compression=gzip"234				alt="size"235		/></a>236	</li>237</ul>238<p>Read further to see all these benefits explained.</p>239<h2>Reducer Example</h2>240<p>241	Here is a simple example of the difference that Immer could make in practice.242</p>243<pre><code class="language-javascript">// Redux reducer244// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js245const byId = (state, action) =&gt; {246	switch (action.type) {247		case RECEIVE_PRODUCTS:248			return {249				...state,250				...action.products.reduce((obj, product) =&gt; {251					obj[product.id] = product252					return obj253				}, {})254			}255		default:256			return state257	}258}259</code></pre>260<p>After using Immer, that simply becomes:</p>261<pre><code class="language-javascript">import produce from &quot;immer&quot;262263const byId = (state, action) =&gt;264	produce(state, draft =&gt; {265		switch (action.type) {266			case RECEIVE_PRODUCTS:267				action.products.forEach(product =&gt; {268					draft[product.id] = product269				})270		}271	})272</code></pre>273<p>274	Notice that it is not needed to handle the default case, a producer that275	doesn't do anything will simply return the original state.276</p>277<p>278	Creating Redux reducer is just a sample application of the Immer package.279	Immer is not just designed to simplify Redux reducers. It can be used in any280	context where you have an immutable data tree that you want to clone and281	modify (with structural sharing).282</p>283<p>284	<em285		>Note: it might be tempting after using producers for a while, to just place286		<code>produce</code> in your root reducer and then pass the draft to each287		reducer and work directly over such draft. Don't do that. It kills the point288		of Redux where each reducer is testable as pure reducer. Immer is best used289		when applying it to small individual pieces of logic.</em290	>291</p>292<h2>React.setState example</h2>293<p>294	Deep updates in the state of React components can be greatly simplified as295	well by using immer. Take for example the following onClick handlers (Try in296	<a href="https://codesandbox.io/s/m4yp57632j">codesandbox</a>):297</p>298<pre><code class="language-javascript">/**299 * Classic React.setState with a deep merge300 */301onBirthDayClick1 = () =&gt; {302	this.setState(prevState =&gt; ({303		user: {304			...prevState.user,305			age: prevState.user.age + 1306		}307	}))308}309310/**311 * ...But, since setState accepts functions,312 * we can just create a curried producer and further simplify!313 */314onBirthDayClick2 = () =&gt; {315	this.setState(316		produce(draft =&gt; {317			draft.user.age += 1318		})319	)320}321</code></pre>322<h2>Currying</h2>323<p>324	Passing a function as the first argument to <code>produce</code> is intended325	to be used for currying. This means that you get a pre-bound producer that326	only needs a state to produce the value from. The producer function gets327	passed in the draft and any further arguments that were passed to the curried328	function.329</p>330<p>For example:</p>331<pre><code class="language-javascript">// mapper will be of signature (state, index) =&gt; state332const mapper = produce((draft, index) =&gt; {333	draft.index = index334})335336// example usage337console.dir([{}, {}, {}].map(mapper))338//[{index: 0}, {index: 1}, {index: 2}])339</code></pre>340<p>341	This mechanism can also nicely be leveraged to further simplify our example342	reducer:343</p>344<pre><code class="language-javascript">import produce from &quot;immer&quot;345346const byId = produce((draft, action) =&gt; {347	switch (action.type) {348		case RECEIVE_PRODUCTS:349			action.products.forEach(product =&gt; {350				draft[product.id] = product351			})352			return353	}354})355</code></pre>356<p>357	Note that <code>state</code> is now factored out (the created reducer will358	accept a state, and invoke the bound producer with it).359</p>360<p>361	If you want to initialize an uninitialized state using this construction, you362	can do so by passing the initial state as second argument to363	<code>produce</code>:364</p>365<pre><code class="language-javascript">import produce from &quot;immer&quot;366367const byId = produce(368	(draft, action) =&gt; {369		switch (action.type) {370			case RECEIVE_PRODUCTS:371				action.products.forEach(product =&gt; {372					draft[product.id] = product373				})374				return375		}376	},377	{378		1: {id: 1, name: &quot;product-1&quot;}379	}380)381</code></pre>382<h5>Fun with currying</h5>383<p>384	A random fun example just for inspiration: a neat trick is to turn385	<code>Object.assign</code> into a producer to create a &quot;spread&quot;386	function that is smarter than the normal spread operator, as it doesn't387	produce a new state if the result doesn't actually change (<a388		href="https://twitter.com/mweststrate/status/1045059430256119809"389		>details &amp; explanation</a390	>). Quick example:391</p>392<pre><code class="language-javascript">import produce from &quot;immer&quot;393const spread = produce(Object.assign)394395const base = {x: 1, y: 1}396397console.log({...base, y: 1} === base) // false398console.log(spread(base, {y: 1}) === base) // true! base is recycled as no actual new value was produced399console.log(spread(base, {y: 2}) === base) // false, produced a new object as it should400</code></pre>401<h2>Patches</h2>402<p>403	During the run of a producer, Immer can record all the patches that would404	replay the changes made by the reducer. This is a very powerful tool if you405	want to fork your state temporarily and replay the changes to the original.406</p>407<p>Patches are useful in few scenarios:</p>408<ul>409	<li>410		To exchange incremental updates with other parties, for example over411		websockets412	</li>413	<li>414		For debugging / traces, to see precisely how state is changed over time415	</li>416	<li>417		As basis for undo/redo or as an approach to replay changes on a slightly418		different state tree419	</li>420</ul>421<p>422	To help with replaying patches, <code>applyPatches</code> comes in handy. Here423	is an example how patches could be used to record the incremental updates and424	(inverse) apply them:425</p>426<pre><code class="language-javascript">import produce, {applyPatches} from &quot;immer&quot;427428let state = {429	name: &quot;Micheal&quot;,430	age: 32431}432433// Let's assume the user is in a wizard, and we don't know whether434// his changes should end up in the base state ultimately or not...435let fork = state436// all the changes the user made in the wizard437let changes = []438// the inverse of all the changes made in the wizard439let inverseChanges = []440441fork = produce(442	fork,443	draft =&gt; {444		draft.age = 33445	},446	// The third argument to produce is a callback to which the patches will be fed447	(patches, inversePatches) =&gt; {448		changes.push(...patches)449		inverseChanges.push(...inversePatches)450	}451)452453// In the meantime, our original state is replaced, as, for example,454// some changes were received from the server455state = produce(state, draft =&gt; {456	draft.name = &quot;Michel&quot;457})458459// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!460state = applyPatches(state, changes)461462// state now contains the changes from both code paths!463expect(state).toEqual({464	name: &quot;Michel&quot;, // changed by the server465	age: 33 // changed by the wizard466})467468// Finally, even after finishing the wizard, the user might change his mind and undo his changes...469state = applyPatches(state, inverseChanges)470expect(state).toEqual({471	name: &quot;Michel&quot;, // Not reverted472	age: 32 // Reverted473})474</code></pre>475<p>476	The generated patches are similar (but not the same) to the477	<a href="http://tools.ietf.org/html/rfc6902">RFC-6902 JSON patch standard</a>,478	except that the <code>path</code> property is an array, rather than a string.479	This makes processing patches easier. If you want to normalize to the official480	specification, <code>patch.path = patch.path.join(&quot;/&quot;)</code> should481	do the trick. Anyway, this is what a bunch of patches and their inverse could482	look like:483</p>484<pre><code class="language-json">[485	{486		&quot;op&quot;: &quot;replace&quot;,487		&quot;path&quot;: [&quot;profile&quot;],488		&quot;value&quot;: {&quot;name&quot;: &quot;Veria&quot;, &quot;age&quot;: 5}489	},490	{&quot;op&quot;: &quot;remove&quot;, &quot;path&quot;: [&quot;tags&quot;, 3]}491]492</code></pre>493<pre><code class="language-json">[494	{&quot;op&quot;: &quot;replace&quot;, &quot;path&quot;: [&quot;profile&quot;], &quot;value&quot;: {&quot;name&quot;: &quot;Noa&quot;, &quot;age&quot;: 6}},495	{&quot;op&quot;: &quot;add&quot;, &quot;path&quot;: [&quot;tags&quot;, 3], &quot;value&quot;: &quot;kiddo&quot;}496]497</code></pre>498<h3><code>produceWithPatches</code></h3>499<p>500	Instead of setting up a patch listener, an easier way to obtain the patches is501	to use <code>produceWithPatches</code>, which has the same signature as502	<code>produce</code>, except that it doesn't return just the next state, but a503	tuple consisting of <code>[nextState, patches, inversePatches]</code>. Like504	<code>produce</code>, <code>produceWithPatches</code> supports currying as505	well.506</p>507<pre><code class="language-javascript">import {produceWithPatches} from &quot;immer&quot;508509const [nextState, patches, inversePatches] = produceWithPatches(510	{511		age: 33512	},513	draft =&gt; {514		draft.age++515	}516)517</code></pre>518<p>Which produces:</p>519<pre><code class="language-javascript">;[520	{521		age: 34522	},523	[524		{525			op: &quot;replace&quot;,526			path: [&quot;age&quot;],527			value: 34528		}529	],530	[531		{532			op: &quot;replace&quot;,533			path: [&quot;age&quot;],534			value: 33535		}536	]537]538</code></pre>539<p>540	For a more in-depth study, see541	<a542		href="https://medium.com/@mweststrate/distributing-state-changes-using-snapshots-patches-and-actions-part-2-2f50d8363988"543		>Distributing patches and rebasing actions using Immer</a544	>545</p>546<p>547	Tip: Check this trick to548	<a549		href="https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69"550		>compress patches</a551	>552	produced over time.553</p>554<h2>Async producers</h2>555<p>556	It is allowed to return Promise objects from recipes. Or, in other words, to557	use <code>async / await</code>. This can be pretty useful for long running558	processes, that only produce the new object once the promise chain resolves.559	Note that <code>produce</code> itself (even in the curried form) will return a560	promise if the producer is async. Example:561</p>562<pre><code class="language-javascript">import produce from &quot;immer&quot;563564const user = {565	name: &quot;michel&quot;,566	todos: []567}568569const loadedUser = await produce(user, async function(draft) {570	draft.todos = await (await window.fetch(&quot;http://host/&quot; + draft.name)).json()571})572</code></pre>573<p>574	<em575		>Warning: please note that the draft shouldn't be 'leaked' from the async576		process and stored else where. The draft will still be revoked as soon as577		the async process completes.</em578	>579</p>580<h2><code>createDraft</code> and <code>finishDraft</code></h2>581<p>582	<code>createDraft</code> and <code>finishDraft</code> are two low-level583	functions that are mostly useful for libraries that build abstractions on top584	of immer. It avoids the need to always create a function in order to work with585	drafts. Instead, one can create a draft, modify it, and at some time in the586	future finish the draft, in which case the next immutable state will be587	produced. We could for example rewrite our above example as:588</p>589<pre><code class="language-javascript">import {createDraft, finishDraft} from &quot;immer&quot;590591const user = {592	name: &quot;michel&quot;,593	todos: []594}595596const draft = createDraft(user)597draft.todos = await (await window.fetch(&quot;http://host/&quot; + draft.name)).json()598const loadedUser = finishDraft(draft)599</code></pre>600<p>601	Note: <code>finishDraft</code> takes a <code>patchListener</code> as second602	argument, which can be used to record the patches, similarly to603	<code>produce</code>.604</p>605<p>606	<em607		>Warning: in general, we recommend to use <code>produce</code> instead of608		the <code>createDraft</code> / <code>finishDraft</code> combo,609		<code>produce</code> is less error prone in usage, and more clearly610		separates the concepts of mutability and immutability in your code base.</em611	>612</p>613<h2>Returning data from producers</h2>614<p>615	It is not needed to return anything from a producer, as Immer will return the616	(finalized) version of the <code>draft</code> anyway. However, it is allowed617	to just <code>return draft</code>.618</p>619<p>620	It is also allowed to return arbitrarily other data from the producer621	function. But <em>only</em> if you didn't modify the draft. This can be useful622	to produce an entirely new state. Some examples:623</p>624<pre><code class="language-javascript">const userReducer = produce((draft, action) =&gt; {625	switch (action.type) {626		case &quot;renameUser&quot;:627			// OK: we modify the current state628			draft.users[action.payload.id].name = action.payload.name629			return draft // same as just 'return'630		case &quot;loadUsers&quot;:631			// OK: we return an entirely new state632			return action.payload633		case &quot;adduser-1&quot;:634			// NOT OK: This doesn't do change the draft nor return a new state!635			// It doesn't modify the draft (it just redeclares it)636			// In fact, this just doesn't do anything at all637			draft = {users: [...draft.users, action.payload]}638			return639		case &quot;adduser-2&quot;:640			// NOT OK: modifying draft *and* returning a new state641			draft.userCount += 1642			return {users: [...draft.users, action.payload]}643		case &quot;adduser-3&quot;:644			// OK: returning a new state. But, unnecessary complex and expensive645			return {646				userCount: draft.userCount + 1,647				users: [...draft.users, action.payload]648			}649		case &quot;adduser-4&quot;:650			// OK: the immer way651			draft.userCount += 1652			draft.users.push(action.payload)653			return654	}655})656</code></pre>657<p>658	<em659		>Note: It is not possible to return <code>undefined</code> this way, as it660		is indistinguishable from <em>not</em> updating the draft! Read on...</em661	>662</p>663<h2>Producing <code>undefined</code> using <code>nothing</code></h2>664<p>665	So, in general, one can replace the current state by just666	<code>return</code>ing a new value from the producer, rather than modifying667	the draft. There is a subtle edge case however: if you try to write a producer668	that wants to replace the current state with <code>undefined</code>:669</p>670<pre><code class="language-javascript">produce({}, draft =&gt; {671	// don't do anything672})673</code></pre>674<p>Versus:</p>675<pre><code class="language-javascript">produce({}, draft =&gt; {676	// Try to return undefined from the producer677	return undefined678})679</code></pre>680<p>681	The problem is that in JavaScript a function that doesn't return anything also682	returns <code>undefined</code>! So immer cannot differentiate between those683	different cases. So, by default, Immer will assume that any producer that684	returns <code>undefined</code> just tried to modify the draft.685</p>686<p>687	However, to make it clear to Immer that you intentionally want to produce the688	value <code>undefined</code>, you can return the built-in token689	<code>nothing</code>:690</p>691<pre><code class="language-javascript">import produce, {nothing} from &quot;immer&quot;692693const state = {694	hello: &quot;world&quot;695}696697produce(state, draft =&gt; {})698produce(state, draft =&gt; undefined)699// Both return the original state: { hello: &quot;world&quot;}700701produce(state, draft =&gt; nothing)702// Produces a new state, 'undefined'703</code></pre>704<p>705	N.B. Note that this problem is specific for the <code>undefined</code> value,706	any other value, including <code>null</code>, doesn't suffer from this issue.707</p>708<h2>Inline shortcuts using <code>void</code></h2>709<p>710	Draft mutations in Immer usually warrant a code block, since a return denotes711	an overwrite. Sometimes that can stretch code a little more than you might be712	comfortable with.713</p>714<p>715	In such cases, you can use javascripts716	<a717		href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void"718		><code>void</code></a719	>720	operator, which evaluates expressions and returns <code>undefined</code>.721</p>722<pre><code class="language-javascript">// Single mutation723produce(draft =&gt; void (draft.user.age += 1))724725// Multiple mutations726produce(draft =&gt; void ((draft.user.age += 1), (draft.user.height = 186)))727</code></pre>728<p>729	Code style is highly personal, but for code bases that are to be understood by730	many, we recommend to stick to the classic731	<code>draft =&gt; { draft.user.age += 1}</code> to avoid cognitive overhead.732</p>733<h2>Extracting the original object from a proxied instance</h2>734<p>735	Immer exposes a named export <code>original</code> that will get the original736	object from the proxied instance inside <code>produce</code> (or return737	<code>undefined</code> for unproxied values). A good example of when this can738	be useful is when searching for nodes in a tree-like state using strict739	equality.740</p>741<pre><code class="language-js">import {original} from &quot;immer&quot;742743const baseState = {users: [{name: &quot;Richie&quot;}]}744const nextState = produce(baseState, draftState =&gt; {745	original(draftState.users) // is === baseState.users746})747</code></pre>748<p>749	Just want to know if a value is a proxied instance? Use the750	<code>isDraft</code> function!751</p>752<pre><code class="language-js">import {isDraft} from &quot;immer&quot;753754const baseState = {users: [{name: &quot;Bobby&quot;}]}755const nextState = produce(baseState, draft =&gt; {756	isDraft(draft) // =&gt; true757	isDraft(draft.users) // =&gt; true758	isDraft(draft.users[0]) // =&gt; true759})760isDraft(nextState) // =&gt; false761</code></pre>762<h2>Auto freezing</h2>763<p>764	Immer automatically freezes any state trees that are modified using765	<code>produce</code>. This protects against accidental modifications of the766	state tree outside of a producer. This comes with a performance impact, so it767	is recommended to disable this option in production. It is by default enabled.768	By default, it is turned on during local development and turned off in769	production. Use <code>setAutoFreeze(true / false)</code> to explicitly turn770	this feature on or off.771</p>772<p>773	<em774		>⚠️ If auto freezing is enabled, recipes are not entirely side-effect free:775		Any plain object or array that ends up in the produced result, will be776		frozen, even when these objects were not frozen before the start of the777		producer! ⚠️</em778	>779</p>780<h2>Immer on older JavaScript environments?</h2>781<p>782	By default <code>produce</code> tries to use proxies for optimal performance.783	However, on older JavaScript engines <code>Proxy</code> is not available. For784	example, when running Microsoft Internet Explorer or React Native (&lt; v0.59)785	on Android. In such cases, Immer will fallback to an ES5 compatible786	implementation which works identical, but is a bit slower.787</p>788<h2>Importing immer</h2>789<p>790	<code>produce</code> is exposed as the default export, but optionally it can791	be used as name import as well, as this benefits some older project setups. So792	the following imports are all correct, where the first is recommended:793</p>794<pre><code class="language-javascript">import produce from &quot;immer&quot;795import {produce} from &quot;immer&quot;796797const {produce} = require(&quot;immer&quot;)798const produce = require(&quot;immer&quot;).produce799const produce = require(&quot;immer&quot;).default800801import unleashTheMagic from &quot;immer&quot;802import {produce as unleashTheMagic} from &quot;immer&quot;803</code></pre>804<h2>Supported object types</h2>805<p>Plain objects and arrays are always drafted by Immer.</p>806<p>807	Every other object must use the <code>immerable</code> symbol to mark itself808	as compatible with Immer. When one of these objects is mutated within a809	producer, its prototype is preserved between copies.810</p>811<pre><code class="language-js">import {immerable} from &quot;immer&quot;812813class Foo {814	[immerable] = true // Option 1815816	constructor() {817		this[immerable] = true // Option 2818	}819}820821Foo[immerable] = true // Option 3822</code></pre>823<p>824	For arrays, only numeric properties and the <code>length</code> property can825	be mutated. Custom properties are not preserved on arrays.826</p>827<p>828	When working with <code>Date</code> objects, you should always create a new829	<code>Date</code> instance instead of mutating an existing830	<code>Date</code> object.831</p>832<p>833	Built-in classes like <code>Map</code> and <code>Set</code> are not supported.834	As a workaround, you should clone them before mutating them in a producer:835</p>836<pre><code class="language-js">const state = {837	set: new Set(),838	map: new Map()839}840const nextState = produce(state, draft =&gt; {841	// Don't use any Set methods, as that mutates the instance!842	draft.set.add(&quot;foo&quot;) // ❌843844	// 1. Instead, clone the set (just once)845	const newSet = new Set(draft.set) // ✅846847	// 2. Mutate the clone (just in this producer)848	newSet.add(&quot;foo&quot;)849850	// 3. Update the draft with the new set851	draft.set = newSet852853	// Similarly, don't use any Map methods.854	draft.map.set(&quot;foo&quot;, &quot;bar&quot;) // ❌855856	// 1. Instead, clone the map (just once)857	const newMap = new Map(draft.map) // ✅858859	// 2. Mutate it860	newMap.set(&quot;foo&quot;, &quot;bar&quot;)861862	// 3. Update the draft863	draft.map = newMap864})865</code></pre>866<h2>TypeScript or Flow</h2>867<p>868	The Immer package ships with type definitions inside the package, which should869	be picked up by TypeScript and Flow out of the box and without further870	configuration.871</p>872<p>873	The TypeScript typings automatically remove <code>readonly</code> modifiers874	from your draft types and return a value that matches your original type. See875	this practical example:876</p>877<pre><code class="language-ts">import produce from &quot;immer&quot;878879interface State {880	readonly x: number881}882883// `x` cannot be modified here884const state: State = {885	x: 0886}887888const newState = produce(state, draft =&gt; {889	// `x` can be modified here890	draft.x++891})892893// `newState.x` cannot be modified here894</code></pre>895<p>896	This ensures that the only place you can modify your state is in your produce897	callbacks. It even works recursively and with <code>ReadonlyArray</code>s!898</p>899<p>900	For curried reducers, the type is inferred from the first argument of recipe901	function, so make sure to type it. The <code>Draft</code> utility type can be902	used if the state argument type is immutable:903</p>904<pre><code class="language-ts">import produce, {Draft} from &quot;immer&quot;905906interface State {907	readonly x: number908}909910// `x` cannot be modified here911const state: State = {912	x: 0913}914915const increment = produce((draft: Draft&lt;State&gt;, inc: number) =&gt; {916	// `x` can be modified here917	draft.x += inc918})919920const newState = increment(state, 2)921// `newState.x` cannot be modified here922</code></pre>923<p><strong>Note:</strong> Immer v1.9+ supports TypeScript v3.1+ only.</p>924<p><strong>Note:</strong> Immer v3.0+ supports TypeScript v3.4+ only.</p>925<h1>Pitfalls</h1>926<ol>927	<li>928		Don't redefine draft like, <code>draft = myCoolNewState</code>. Instead,929		either modify the <code>draft</code> or return a new state. See930		<a href="#returning-data-from-producers">Returning data from producers</a>.931	</li>932	<li>933		Immer assumes your state to be a unidirectional tree. That is, no object934		should appear twice in the tree, and there should be no circular references.935	</li>936	<li>937		Since Immer uses proxies, reading huge amounts of data from state comes with938		an overhead (especially in the ES5 implementation). If this ever becomes an939		issue (measure before you optimize!), do the current state analysis before940		entering the producer function or read from the941		<code>currentState</code> rather than the <code>draftState</code>. Also,942		realize that immer is opt-in everywhere, so it is perfectly fine to manually943		write super performance critical reducers, and use immer for all the normal944		ones. Also note that <code>original</code> can be used to get the original945		state of an object, which is cheaper to read.946	</li>947	<li>948		Always try to pull <code>produce</code> 'up', for example949		<code>for (let x of y) produce(base, d =&gt; d.push(x))</code> is950		exponentially slower than951		<code>produce(base, d =&gt; { for (let x of y) d.push(x)})</code>952	</li>953	<li>954		It is possible to return values from producers, except, it is not possible955		to return <code>undefined</code> that way, as it is indistinguishable from956		not updating the draft at all! If you want to replace the draft with957		<code>undefined</code>, just return <code>nothing</code> from the producer.958	</li>959</ol>960<h2>Cool things built with immer</h2>961<ul>962	<li>963		<a href="https://github.com/aweary/react-copy-write">react-copy-write</a>964		<em>Immutable state with a mutable API</em>965	</li>966	<li>967		<a href="https://github.com/markerikson/redux-starter-kit"968			>redux-starter-kit</a969		>970		<em>A simple set of tools to make using Redux easier</em>971	</li>972	<li>973		<a href="https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8"974			>immer based handleActions</a975		>976		<em>Boilerplate free actions for Redux</em>977	</li>978	<li>979		<a href="https://github.com/anish000kumar/redux-box">redux-box</a>980		<em981			>Modular and easy-to-grasp redux based state management, with least982			boilerplate</em983		>984	</li>985	<li>986		<a href="https://github.com/jeffreyyoung/quick-redux">quick-redux</a>987		<em>tools to make redux development quicker and easier</em>988	</li>989	<li>990		<a href="https://github.com/jamiebuilds/bey">bey</a>991		<em>Simple immutable state for React using Immer</em>992	</li>993	<li>994		<a href="https://github.com/drcmda/immer-wieder#readme">immer-wieder</a>995		<em996			>State management lib that combines React 16 Context and immer for Redux997			semantics</em998		>999	</li>1000	<li>1001		<a href="https://github.com/neurosnap/robodux">robodux</a>1002		<em>flexible way to reduce redux boilerplate</em>1003	</li>1004	<li>1005		<a href="https://github.com/epeli/immer-reducer">immer-reducer</a>1006		<em1007			>Type-safe and terse React (useReducer()) and Redux reducers with1008			Typescript</em1009		>1010	</li>1011	<li>1012		<a href="https://github.com/knpwrs/redux-ts-utils">redux-ts-utils</a>1013		<em1014			>Everything you need to create type-safe applications with Redux with a1015			strong emphasis on simplicity</em1016		>1017	</li>1018	<li>1019		<a href="https://github.com/suchipi/react-state-tree">react-state-tree</a>1020		<em1021			>Drop-in replacement for useState that persists your state into a1022			redux-like state tree</em1023		>1024	</li>1025	<li>1026		<a href="https://github.com/salvoravida/redux-immer">redux-immer</a>1027		<em1028			>is used to create an equivalent function of Redux combineReducers that1029			works with <code>immer</code> state. Like <code>redux-immutable</code> but1030			for <code>immer</code></em1031		>1032	</li>1033	<li>1034		... and <a href="https://www.npmjs.com/browse/depended/immer">many more</a>1035	</li>1036</ul>1037<h2>How does Immer work?</h2>1038<p>1039	Read the (second part of the)1040	<a1041		href="https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3"1042		>introduction blog</a1043	>.1044</p>1045<h2>Example patterns.</h2>1046<p><em>For those who have to go back to thinking in object updates :-)</em></p>1047<pre><code class="language-javascript">import produce from &quot;immer&quot;10481049// object mutations1050const todosObj = {1051	id1: {done: false, body: &quot;Take out the trash&quot;},1052	id2: {done: false, body: &quot;Check Email&quot;}1053}10541055// add1056const addedTodosObj = produce(todosObj, draft =&gt; {1057	draft[&quot;id3&quot;] = {done: false, body: &quot;Buy bananas&quot;}1058})10591060// delete1061const deletedTodosObj = produce(todosObj, draft =&gt; {1062	delete draft[&quot;id1&quot;]1063})10641065// update1066const updatedTodosObj = produce(todosObj, draft =&gt; {1067	draft[&quot;id1&quot;].done = true1068})10691070// array mutations1071const todosArray = [1072	{id: &quot;id1&quot;, done: false, body: &quot;Take out the trash&quot;},1073	{id: &quot;id2&quot;, done: false, body: &quot;Check Email&quot;}1074]10751076// add1077const addedTodosArray = produce(todosArray, draft =&gt; {1078	draft.push({id: &quot;id3&quot;, done: false, body: &quot;Buy bananas&quot;})1079})10801081// delete1082const deletedTodosArray = produce(todosArray, draft =&gt; {1083	draft.splice(draft.findIndex(todo =&gt; todo.id === &quot;id1&quot;), 1)1084	// or (slower):1085	// return draft.filter(todo =&gt; todo.id !== &quot;id1&quot;)1086})10871088// update1089const updatedTodosArray = produce(todosArray, draft =&gt; {1090	draft[draft.findIndex(todo =&gt; todo.id === &quot;id1&quot;)].done = true1091})1092</code></pre>1093<h2>Performance</h2>1094<p>1095	Here is a <a href="__performance_tests__/todo.js">simple benchmark</a> on the1096	performance of Immer. This test takes 50,000 todo items and updates 5,000 of1097	them. <em>Freeze</em> indicates that the state tree has been frozen after1098	producing it. This is a <em>development</em> best practice, as it prevents1099	developers from accidentally modifying the state tree.1100</p>1101<p>1102	These tests were executed on Node 9.3.0. Use <code>yarn test:perf</code> to1103	reproduce them locally.1104</p>1105<p><img src="images/performance.png" alt="performance.png" /></p>1106<p>Most important observation:</p>1107<ul>1108	<li>1109		Immer with proxies is roughly speaking twice to three times slower as a1110		handwritten reducer (the above test case is worst case, see1111		<code>yarn test:perf</code> for more tests). This is in practice negligible.1112	</li>1113	<li>1114		Immer is roughly as fast as ImmutableJS. However, the1115		<em>immutableJS + toJS</em> makes clear the cost that often needs to be paid1116		later; converting the immutableJS objects back to plain objects, to be able1117		to pass them to components, over the network etc... (And there is also the1118		upfront cost of converting data received from e.g. the server to immutable1119		JS)1120	</li>1121	<li>Generating patches doesn't significantly slow down immer</li>1122	<li>1123		The ES5 fallback implementation is roughly twice as slow as the proxy1124		implementation, in some cases worse.1125	</li>1126</ul>1127<h2>Migration</h2>1128<p><strong>Immer 2.* -&gt; 3.0</strong></p>1129<p>1130	In your producers, make sure you're not treating <code>this</code> as the1131	draft. (see here: https://github.com/immerjs/immer/issues/308)1132</p>1133<p>Upgrade to <code>typescript@^3.4</code> if you're a TypeScript user.</p>1134<p><strong>Immer 1.* -&gt; 2.0</strong></p>1135<p>1136	Make sure you don't return any promises as state, because1137	<code>produce</code> will actually invoke the promise and wait until it1138	settles.1139</p>1140<p><strong>Immer 2.1 -&gt; 2.2</strong></p>1141<p>1142	When using TypeScript, for curried reducers that are typed in the form1143	<code>produce&lt;Type&gt;((arg) =&gt; { })</code>, rewrite this to1144	<code>produce((arg: Type) =&gt; { })</code> or1145	<code>produce((arg: Draft&lt;Type&gt;) =&gt; { })</code> for correct1146	inference.1147</p>1148<h2>FAQ</h2>1149<p><em>(for those who skimmed the above instead of actually reading)</em></p>1150<p>1151	<strong1152		>Q: Does Immer use structural sharing? So that my selectors can be memoized1153		and such?</strong1154	>1155</p>1156<p>A: Yes</p>1157<p><strong>Q: Does Immer support deep updates?</strong></p>1158<p>A: Yes</p>1159<p>1160	<strong1161		>Q: I can't rely on Proxies being present on my target environments. Can I1162		use Immer?</strong1163	>1164</p>1165<p>A: Yes</p>1166<p><strong>Q: Can I typecheck my data structures when using Immer?</strong></p>1167<p>A: Yes</p>1168<p>1169	<strong1170		>Q: Can I store <code>Date</code> objects, functions etc in my state tree1171		when using Immer?</strong1172	>1173</p>1174<p>A: Yes</p>1175<p><strong>Q: Is it fast?</strong></p>1176<p>A: Yes</p>1177<p><strong>Q: Idea! Can Immer freeze the state for me?</strong></p>1178<p>A: Yes</p>1179<h2>Credits</h2>1180<p>1181	Special thanks to @Mendix, which supports its employees to experiment1182	completely freely two full days a month, which formed the kick-start for this1183	project.1184</p>1185<h2>Donations</h2>1186<p>1187	A significant part of my OSS work is unpaid. So1188	<a href="https://mobx.js.org/donate.html">donations</a> are greatly1189	appreciated :)1190</p>