Streamlining State Management in Storybook with React

  • Publish Date
  • Reading Time
    3 minutes
  • Tags
    • react
    • infra
Tweet

    Storybook is an amazing tool for developing UI components in isolation. One of my current projects is a large form with controlled components that rely on their parent container as the source of truth. While Storybook is great for testing individual component state, I found myself writing repetitive code in each story to pass state to a parent container.

    Loading...

    This parent component could easily be abstracted and imported into relevant stories, but since each story is effectively a render function you would ideally pass the state variables through as arguments, i.e.

    Loading...

    To solve this, I created two components and a custom decorator in the .storybook/config.js file. The first component is a function-as-child that acts as a render callback, emulating the parent component from my project. The second is a presentation component that receives state as a prop and displays the current value below each story. The custom decorator adds these components and state variables to each story, where the components wrap the story and the state values are passed as arguments.

    Loading...

    This allows each component to easily set and retrieve hoisted state values from the story itself, without any extra code. ๐Ÿ’ฅ

    Enjoying the article?

    Support the content
    Loading...

    You can find the repository on GitHub, and hereโ€™s a quick look at it in action:

    1.1: Test both controlled and uncontrolled inputs in Storybook
    1.1: Test both controlled and uncontrolled inputs in Storybook

    Related Articles