storybook: [Bug]: Storybook preview hooks can only be called inside decorators and story functions.

Describe the bug

When attempting to use a custom render function to create a Story for a controlled component, I am getting the following error.

Storybook preview hooks can only be called inside decorators and story functions.

This previously worked fine, so I am curious what changed.

My Story code is as follows. I am just trying to use a basic implementation of useState. The Story renders correctly, but as soon as I press the Button, this error is displayed.

From what I can tell, this is being caused by @storybook/addon-themes. You can see my setup in the reproduction.

// .storybook/preview.ts
import type { Preview, ReactRenderer } from '@storybook/react';
import { withThemeByDataAttribute } from '@storybook/addon-themes';

const preview: Preview = {
  parameters: {
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/i,
      },
    },
  },
  decorators: [
    withThemeByDataAttribute<ReactRenderer>({
      themes: {
        light: 'light',
        dark: 'dark',
        auto: 'auto',
      },
      defaultTheme: 'light',
      attributeName: 'data-color-mode',
    }),
  ],
};

export default preview;

type Story = StoryObj<typeof meta>;

export const Controlled: Story = {
  args: {
    size: 'small',
    label: 'Button',
  },
  render: function Render(args) {
    const [pressed, setPressed] = React.useState(false);

    return (
      <>
        <Button {...args} onClick={() => setPressed(!pressed)} />
        <h1>{pressed.toString()}</h1>
      </>
    );
  },
};

Reproduction link

https://stackblitz.com/edit/github-rjewa6?file=.storybook%2Fpreview.ts

Reproduction steps

  1. Run the Storybook.
  2. Navigate to the Button -> Controlled Story
  3. Press the button

System

Storybook Environment Info:

  System:
    OS: macOS 15.0
    CPU: (14) arm64 Apple M3 Max
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.16.0 - ~/.nvm/versions/node/v20.16.0/bin/node
    npm: 10.8.1 - ~/.nvm/versions/node/v20.16.0/bin/npm
    pnpm: 9.6.0 - ~/Library/pnpm/.tools/pnpm/9.6.0/bin/pnpm <----- active
  Browsers:
    Chrome: 129.0.6668.58
    Safari: 18.0

Additional context

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 39
  • Comments: 30 (4 by maintainers)

Commits related to this issue

Most upvoted comments

Also facing the exact same issue, which appeared in version 8.3.0. For the moment, staying on 8.2.9 prevent the issue.

Working on a fix to finally solve this properly in Storybook 9!

@vanessayuenn I think we should put this as high priority in the empathy workstream.

Facing the same issue, it started happening with 8.3.0. It works fine till 8.2.9. I have the pretty much the same story example as given in description.

@yannbf This issue is really complicated and in fundamental way, this was broken for quite some time.

The issue seemed to have been aggravated by a RSC decorator change.

Here is a PR that should fix that issue: https://github.com/storybookjs/storybook/pull/26243

There will still be a problem when a user write a chain of decerator like this itself:

    withThemeByDataAttribute<ReactRenderer>({
      themes: {
        light: 'light',
        dark: 'dark',
        auto: 'auto',
      },
      defaultTheme: 'light',
      attributeName: 'data-color-mode',
    }),
    // We have something like this decorator now by default in React since 8.3.0
    // But you get the same error with a custom decorator, that doesn't use storyFn.
    (Story) => {
      return <Story />;
    },

Or even a custom decorator that uses the storybook context in some way:

    (storyFn) => {
      useParameter("bla", {});
      return storyFn();
    },
    (Story) => {
      return <Story />;
    },

This is a very weird issue. We are not yet at the bottom of this problem.

We might be able to prevent it with a custom applyDecorator, in a similar way that Vue has:

https://github.com/storybookjs/storybook/blob/1fdd2d6c675b81269125af5027e45a357c09f1fa/code/renderers/vue3/src/decorateStory.ts#L47-L80

And add a (S) => decorator in between each other decorator in the stack. After some experimenting it seems that React doesn’t loose its react state in this way.

Had the same issue on my end, fixed it by using the useState from preview-api instead of React’s

- import { useState } from "react";
+ import { useState } from "storybook/internal/preview-api";

Currently on storybook@8.4.7

version 8.5.0 also solved the issue for me 👍

UPD: The following recommendation helped me - https://stackoverflow.com/a/77859321/10963661. I moved the withThemeFromJSXProvider definition to the last place in the decorators array. And then replaced hooks imports back with the import { useState } from 'react'. After that - the stories finally started working again!

Simply adding “async” to my component broke it. This suggestion worked for me, but I had to add the <React.Suspense> wrapper.

	decorators: [
		/**
		 * This is a workaround to fix an issue with the "withThemeByClassName" and React Server Components
		 * see https://github.com/storybookjs/storybook/issues/29189#issuecomment-2573457548
		 *
		 * Error: Storybook preview hooks can only be called inside decorators and story functions.
		 * 	at invalidHooksError (http://localhost:6006/sb-preview/runtime.js:3668:7)
		 * 	at useStoryContext (http://localhost:6006/sb-preview/runtime.js:3783:11)
		 * 	at useParameter (http://localhost:6006/sb-preview/runtime.js:3788:27)
		 * 	at useThemeParameters (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_client_ReactRefreshEntry_js-node_mod-412678.iframe.bundle.js:14928:684)
		 * */
		storyFn => {
			return <React.Suspense>{storyFn() as React.ReactNode}</React.Suspense>;
		},
		withThemeByClassName({
			themes: {
				// nameOfTheme: 'classNameForTheme',
				light: '',
				dark: 'dark',
			},
			defaultTheme: 'light',
		}),
	],

Seems to be fixed in 8.5.0.

What is status here, @kasperpeulen? Have you gotten a solution/fix yet? I have the same issue in Angular.

I get the same thing with Storybook 9.0.6 using @storybook/nextjs. However, I get it only in async stories with features.experimentalRSC: true in .storybook/main.ts and:

  • In dev mode, it happens only when a bunch of updates happen in quick succession (e.g. holding the backspace button to delete text)
  • In prod mode, the error is shown immediately when the story is loaded

My guess is that there’s some kind of race condition between useArgs in async RSC components. Perhaps the component takes too long, so useArgs of a previous render is called when a new render is already in process.

This is still a problem. In my case I’m using the useDarkMode from storybook-dark-mode which I assume it must have an useState.

version 8.5.0 also solved the issue for me 👍

I’m on 8.5.1 and seeing this error. It’s intermittent which doesn’t make a lot of sense to me 😃. If I constantly refresh the page eventually the error goes away and my component renders. But that’s not a solution only an observation.

https://github.com/user-attachments/assets/b4252ebf-49fc-4295-995e-ae1daafdec3b

// ImageCropper.stories.tsx
// ... meta above
export const Default: Story = {
  render: function Render(args) {
    const [{ zoom, crop }, updateArgs] = useArgs<typeof args>();

    const {
      setZoom,
      setCrop,
      onCropComplete,
      // zoom: componentZoom,
      // crop: componentCrop,
      ...rest
    } = useImageCropper({
      initialZoom: zoom,
      initialCrop: crop,
    });

    const handleZoom: ImageCropperProps['setZoom'] = (value) => {
      const newZoom = typeof value === 'function' ? value(zoom) : value;
      updateArgs({ zoom: newZoom });
      args.setZoom(newZoom);
      setZoom(newZoom);
    };

    const handleCrop: ImageCropperProps['setCrop'] = (value) => {
      const newCrop = typeof value === 'function' ? value(crop) : value;
      updateArgs({ crop: newCrop });
      args.setCrop(newCrop);
      setCrop(newCrop);
    };

    const handleCropComplete: ImageCropperProps['onCropComplete'] = (
      croppedArea,
      croppedAreaPixels,
    ) => {
      onCropComplete(croppedArea, croppedAreaPixels);
      args.onCropComplete(croppedArea, croppedAreaPixels);
    };

    return (
      <div className="h-[400px] w-[400px]">
        <ImageCropper
          {...rest}
          imageSrc={args.imageSrc}
          setZoom={handleZoom}
          setCrop={handleCrop}
          onCropComplete={handleCropComplete}
        />
      </div>
    );
  },
};

I was having the same issue in 8.4.7. Not using @storybook/addon-themes fixed it.

UPD: The following recommendation helped me - https://stackoverflow.com/a/77859321/10963661. I moved the withThemeFromJSXProvider definition to the last place in the decorators array. And then replaced hooks imports back with the import { useState } from 'react'. After that - the stories finally started working again!

Simply adding “async” to my component broke it. This suggestion worked for me, but I had to add the <React.Suspense> wrapper.

	decorators: [
		/**
		 * This is a workaround to fix an issue with the "withThemeByClassName" and React Server Components
		 * see https://github.com/storybookjs/storybook/issues/29189#issuecomment-2573457548
		 *
		 * Error: Storybook preview hooks can only be called inside decorators and story functions.
		 * 	at invalidHooksError (http://localhost:6006/sb-preview/runtime.js:3668:7)
		 * 	at useStoryContext (http://localhost:6006/sb-preview/runtime.js:3783:11)
		 * 	at useParameter (http://localhost:6006/sb-preview/runtime.js:3788:27)
		 * 	at useThemeParameters (http://localhost:6006/vendors-node_modules_pmmmwh_react-refresh-webpack-plugin_client_ReactRefreshEntry_js-node_mod-412678.iframe.bundle.js:14928:684)
		 * */
		storyFn => {
			return <React.Suspense>{storyFn() as React.ReactNode}</React.Suspense>;
		},
		withThemeByClassName({
			themes: {
				// nameOfTheme: 'classNameForTheme',
				light: '',
				dark: 'dark',
			},
			defaultTheme: 'light',
		}),
	],

Unfortunately, I still experience the same exception even after downgrading to the 8.2.10 version!

Here’s the story template I use:

const InteractiveStudentTemplate = (args) => {
	const { ... } = args;

	const [submitting, setSubmitting] = useState(false);
	const handleChoiceSelected = (choiceFamilyId: FamilyId) => {
		setSubmitting(true);
	};

	return <button onClick={() => setSubmitting(true)}>Click me!</button>;
};

export const PollQuestion = InteractiveStudentTemplate.bind({});
PollQuestion.args = {
	...
}

Whenever I click on the button - the screen flashes with the exception:

https://github.com/user-attachments/assets/065934e8-ddf1-44c2-ba02-5491e5999ed5


The approach recommended by @damonaskavio helps, and after replacing the useState imports with import { useState } from "storybook/internal/preview-api"; - story renders successfully locally ✅. However, the same exception is thrown when the stories are being rendered within the jest runtime ❌


UPD: The following recommendation helped me - https://stackoverflow.com/a/77859321/10963661. I moved the withThemeFromJSXProvider definition to the last place in the decorators array. And then replaced hooks imports back with the import { useState } from 'react'. After that - the stories finally started working again!

A not so ideal work around is:

export function Story() {
    return ComponentDecorator(Component);
}

I love the Empathy Backlog name. Sending warm vibes to Storybook comrades.

Just notice this same issue today. Every story that has a useState is broken 😦

The same problem happens to me as well. Here is reproduction: chromatic preview, code