In this article, you will learn how to configure DevTools for your Zustand store. We will use the Lobechat source code and Zustand documentation as our reference.
The question to ask here is how is this different from the simple createStore API without DevTools. In the Create a store documentation,
you will see this below code snippet:
It is easy to understand that the third parameter is the action name, but why is the second parameter above is defined as undefined. I found the below statements about this undefined parameter in the documentation.
Additionally, to preserve the default behavior of the replacement logic, the second parameter should be set to undefined.
Do not set the second parameter to true or false unless you want to override the
default replacement logic
Now that we understand the basics of configuring DevTools for a Zustand store. Let’s review the code in Lobechat Zustand store.
Instead of directly importing devtools from zustand/middleware. createDevTools is a function imported from createDevTools.ts and has the below code:
import { optionalDevtools } from 'zustand-utils';import { devtools as _devtools } from 'zustand/middleware';import { isDev } from '@/utils/env';export const createDevtools = (name: string): typeof _devtools => (initializer) => { let showDevtools = false; // check url to show devtools if (typeof window !== 'undefined') { const url = new URL(window.location.href); const debug = url.searchParams.get('debug'); if (debug?.includes(name)) { showDevtools = true; } } return optionalDevtools(showDevtools)(initializer, { name: `LobeChat_${name}` + (isDev ? '_DEV' : ''), }); };
This code tells us that if the url contains a query param named showDevtools and is true, only then show DevTools and uses optionalDevTools imported from zustand-utils.
Often times, concepts found in documentation are not implemented as is in the open-source, this above way of configuring debugging demonstrates that developers at LobeChat are extremely good at what they do.
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.