DEV Community

Cover image for useDebugValue usage in Zustand source code explained.
thinkThroo
thinkThroo

Posted on

useDebugValue usage in Zustand source code explained.

In this article, we will understand how useDebugValue is used in Zustand’s source code.

Image description

useDebugValue is used in a function named useStoreWithEquality. useDebugValue is a React Hook that lets you add a label to a custom Hook in React DevTools.

Call useDebugValue at the top level of your custom Hook to display a readable debug value:

// Pulled from https://react.dev/reference/react/useDebugValue
import { useDebugValue } from 'react';

function useOnlineStatus() {
  // ...
  useDebugValue(isOnline ? 'Online' : 'Offline');
  // ...
}
Enter fullscreen mode Exit fullscreen mode

Image description

In Zustand, useDebugValue is used on slice an object that looks like below:

const slice = useSyncExternalStoreWithSelector(
  api.subscribe,
  api.getState,
  api.getInitialState,
  selector,
  equalityFn,
)
Enter fullscreen mode Exit fullscreen mode

useDebugValue is also used in src/react.ts

About us:

At Think Throo, we are on a mission to teach the best practices inspired by open-source projects.

10x your coding skills by practising advanced architectural concepts in Next.js/React, learn the best practices and build production-grade projects.

We are open source — https://github.com/thinkthroo/thinkthroo (Do give us a star!)

Up skill your team with our advanced courses based on codebase architecture. Reach out to us at hello@thinkthroo.com to learn more!

References:

  1. https://github.com/pmndrs/zustand/blob/main/src/traditional.ts#L51

  2. https://react.dev/reference/react/useDebugValue

  3. https://github.com/pmndrs/zustand/blob/0a4f9d0f71477c5ef399191acc19e25674d0d3c4/src/react.ts#L42



Top comments (1)

Collapse
 
sempai07 profile image
Sempai-07

Nice