Mocking React Context in Storybook

Creating simple decorators to mock React Context for your Stories

John Clarke
5 min readJan 13, 2022

Recently I’ve been building a lot of front end code using React/NextJS, Tailwind and Storybook to achieve a component first development workflow that I’ve written a number of articles about. If you’re using React heavily you’ve more than likely created components that use React Context and a custom hook to handle global state and cross-cutting concerns — I’m a big fan of creating custom contexts and hooks for this as it’s a pattern I found works really well. However, if you follow this pattern and use Storybook you’ll eventually run into a problem; if you try to render your components in Storybook with out a suitable Context.Provider to wrap them, they’ll generate an error. Additionally, to isolate your components and render them in specific states, you’ll want to push specific state into the context for the component to pick up. Fortunately, with Storybook’s ‘Decorators’ the solution is actually very simple!

All of the code for this article can be found in my GitHub at https://github.com/TheMagoo73/storybook-context-demo.

Starting with a contrived example!

Let’s start with a pretty contrived example. If you run the app from the repo linked above you’ll see a NextJS app that…

--

--

John Clarke
John Clarke

Written by John Clarke

Director of Software Development; Agile and GitOps evangelist. Currently building great software with my awesome team!

Responses (1)