Create an Addon
  • Introduction
  • Setup
  • Register addon
  • Track state
  • Decorators
  • Preset
  • Add to catalog
  • Conclusion

Track state

Manage addon state across the Manager and Preview

React has built in hooks, such as useState, to manage state. Usually, this would be enough. However, in this case things are slightly more complicated. Let’s take a moment to talk about how Storybook is architected.

Basics of Storybook’s architecture

manager preview

On the surface, Storybook presents a unified user interface. However, under the hood it’s divided into two segments that talk to each other across a communication channel:

  • A Manager: the UI where Storybook’s search, navigation, toolbars, and addons are rendered.
  • Preview: an iframe where the stories are rendered.

We need to track the toggle state and we also need to share that state across both the Manager and Preview. Therefore, instead of useState we are going to use useGlobals from @storybook/api.

Track global state

Globals represent the “global” (as in not story-specific) context in Storybook. They are a handy way to share information between different stories, addons and decorators. The useGlobals hook that allows you to access this global context within the tool that you’re building.

Checkout @storybook/addons for more addons related APIs.

The Addon Kit preconfigures the Tool to use globals. Let’s rename the global to more accurately reflect what it does. The toggleOutline function allows the user to actually toggle the outline addon on and off 👉🏽🔘

The tool track toggle state

import React, { useCallback } from 'react';
import { useGlobals } from '@storybook/api';
import { Icons, IconButton } from '@storybook/components';
import { TOOL_ID } from './constants';

export const Tool = () => {
+  const [{ outlineActive }, updateGlobals] = useGlobals();

+  const toggleOutline = useCallback(
    () =>
+        outlineActive: !outlineActive,
+    [outlineActive]

  return (
+      active={outlineActive}
      title="Apply outlines to the preview"
+      onClick={toggleOutline}
      <Icons icon="outline" />
Keep your code in sync with this chapter. View ffd9ccb on GitHub.
Is this free guide helping you? Tweet to give kudos and help other devs find it.
Next Chapter
Interacting with the stories
✍️ Edit on GitHub – PRs welcome!
Add Storybook to your project in less than a minute to build components faster and easier.
Learn Storybook with in-depth tutorials that teaches Storybook best practices. Follow along with code samples.
Learn Storybook now
The MIT License (MIT). Website design by @domyen and the awesome Storybook community.
StorybookShowcaseDocsTutorialsAddonsBlogReleasesGet involvedUse casesSupportTelemetryTeam
Community GitHub Twitter Discord chat Youtube Component Driven UIs
Get news, free tutorials, and Storybook tips emailed to you.

Maintained by
Continuous integration by
Hosting by