Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for How to migrate Zustand from Version 3 to 4
Diego (Relatable Code)
Diego (Relatable Code)

Posted on • Originally published atrelatablecode.com on

     

How to migrate Zustand from Version 3 to 4

Introduction

Zustand is an awesome state management library for React that excels in its simplicity. It's just one hook that can then be called from anywhere in the app to access yourstore.

This simplicity has made it the perfect choice for personal small-medium sized apps because it requires little boilerplate and it comes baked in with some awesome middleware!

As an aside middleware is:

such as:

  • Persisting to local storage
  • Immer to make state changes easier to handle
  • Store version and migration handling

I used this library to handle persisted data in a personal app ofmine. Essentially it's a CRUD app to manage Pokemon you run into in a playthrough of a game.

The important part however is that I have anobsession with keeping my libraries up-to-date (specifically in these small personal apps) so I decided to go ahead and migrate Zustand from version 3 to 4.

As a small disclaimer, this article assumes you have some base-level experience with Zustand.

Migration Process

First and foremost you can check out the changelog and any specific changes you may need to do on theZustand GitHub repo changelog.

First, let’s go ahead and update the library:

yarn add zustand
Enter fullscreen modeExit fullscreen mode

In my case, it updated to 4.1.1.

All the previous APIs are backward compatible so keep in mind that the changes I’m going to make apply to Typescript.

Immer is a library that allows you to work with immutable state data in a more convenient way. Before we had to explicitly set the type like this and the function to use it:

const immer =  <T extends State>(config: StateCreator<T>): StateCreator<T> =>  (set, get, api) =>    config(      (partial, replace) => {        const nextState =          typeof partial === 'function' ? produce(partial as (state: T) => T) : (partial as T);        return set(nextState, replace);      },      get,      api    );
Enter fullscreen modeExit fullscreen mode

However, we can now just import it directly from Zustand’s middleware, so we can delete the above code.

import { immer } from 'zustand/middleware/immer';
Enter fullscreen modeExit fullscreen mode

Next, the section where you’re creating the store requires a small change:

const useStore = create<AppState>(
Enter fullscreen modeExit fullscreen mode

to

const useStore = create<AppState>()(
Enter fullscreen modeExit fullscreen mode

It is now treated as a curried function.

Last but not least, I used the migrate option in the PersisOptions that Zustand provides to persist all data to local storage. However, the state of this app is now considered unknown by Typescript.

We can fix this by explicitly declaring the type with an assert function. For the sake of brevity I did something like this:

migrate: (persistedState, version) => { assertAppState(persistedState);
Enter fullscreen modeExit fullscreen mode

The assert function looks something like this:

function assertAppState(val: unknown): asserts val is AppState {  if (typeof val !== 'object') {    throw new TypeError('Invalid app state');  }}
Enter fullscreen modeExit fullscreen mode

This means anytime I call my state object afterward in the migrate function then it will have the correct typing rather than unknown.

Wrapping it up

Zustand is an awesome library that is simple to use. I recommend using it in any project you may be working on. If you have any other questions or stories about your migration process leave them in the comments below!

Let’s connect

If you liked this feel free to connect with me onLinkedIn orTwitter

Check out my free developer roadmap and weekly tech industry news in mynewsletter.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

🚀 JS/React/Typescript Developer 🛠️ Self-taught developerNew articles every MondayLet's connect on Twitter https://twitter.com/relatablecoder
  • Location
    Bogota D.C., Colombia
  • Work
    Senior Developer
  • Joined

More fromDiego (Relatable Code)

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp