Reading time: 2 min read

Fix Storybook React Hook Errors on Sitecore JSS 21.6.0 and Up

Sitecore JavaScript Services (JSS) 21.6.0 was recently released with many improvements over JSS 21.5.X. One of the introduced changes can however prevent you from using Storybook.

Portrait photo of Jeff L'Heureux, article author

React Hook Errors When Running Storybook

When installing and running Storybook (7.6.10 in my case) in a project from the latest xmcloud-foundation-head repository with JSS 21.6.0 or above or a project created with npx create-sitecore-jss with the nextjs template, no component are showing in Storybook and we get browser console errors:

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

Uncaught TypeError: Cannot read properties of null (reading 'useRef')
    at useRef (react.development.js:1630:1)
    at WithCallback (react-18.mjs:4:1)
    at renderWithHooks (react-dom.development.js:10732:1)
    at mountIndeterminateComponent (react-dom.development.js:15770:1)
    at beginWork$1 (react-dom.development.js:17354:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:19467:1)
    at Object.invokeGuardedCallbackImpl (react-dom.development.js:19516:1)
    at invokeGuardedCallback (react-dom.development.js:19591:1)
    at beginWork (react-dom.development.js:25733:1)
    at performUnitOfWork (react-dom.development.js:24557:1)

After comparing the project files with a JSS 21.5.X project, we identified the change that breaks Storybook is from this JSS repository pull request. The path of React was changed from ["node_modules/@types/react"] to ["node_modules/react"] in the tsconfig.json file.

Fixing the Storybook Errors

Reverting this change in our project resolved the Storybook issues.

  1. Open the tsconfig.json file.
  2. Revert the compilerOptions.paths.react from ["node_modules/react"] to ["node_modules/@types/react"].
  3. Save the file.
  4. Run Storybook again.

Happy Storybooking!