• Home
  • Blog
  • Projects
  • Bookshelf
  • About
← Back to all posts

Managing Complex UI Component State

Published ....
Last modified ....

Share this post on BlueskySee discussion on Bluesky


Managing state in React is difficult. While many suggest that lifting state up to the highest level of the app, and frequently even outside of the component tree, most apps aren't that simple.

One case where this becomes complicated is when app authors need to interact with complex UI components within their application. I internally wrestle with this concept frequently as I build these UI components everyday at work.

One of the most recent cases where I am running into this is our new carousel component which I started work on about 6 months ago as of the time of writing this blog post. This component is perhaps the most complicated UI component we have at Wayfair.

It manages quite a bit of internal state, ranging from actual React state to many references to the rendered dom nodes as well. The problem here is that we also want end users (app developers) the ability to control the carousel from their business logic.

We started with the concept that render props and prop getters would be sufficient to allow end users to control the carousel, however over the months of development, we realized that many (maybe 90%) of frontend developers at Wayfair (and really anywhere) don't want to manage a lot of state and helpers that comes with a render prop.

So we mostly scrapped the render prop pattern on the carousel

[1]Jump to footnote

. Since then we have continued to iterate on the carousel but we were still blocked by this battle of how to properly let end developers control the carousel while also not needing to manage a ton of internal logic (and possibly duplicating that across the codebase).

Skip forward ~ 2 months

On Memorial day weekend of 2018, I decided to spend some time in Codesandbox to work on this problem. One of the rough patterns that I still don't fully grasp from the Downshift component published by Paypal, is the idea of passing back up functions in event handlers to help compute the next state

[2]Jump to footnote

.

I started with a simple example, a component that can be both controlled as well as uncontrolled (a counter component). I broke the problem down into two pieces:

  1. Local state management
  2. External state management

The common logic between these two pieces is the actual methods behind how to update this state. Locally we call setState with either an object or a function. Using an object for setState generally means that we have all the information we need to determine the next state. Whereas using a function means that we need to know the current state of the world to derive the next state.

As with a counting component, a carousel only really needs to know the current slide, the action the user is taking (i.e. clicking next), and the number of slides to scroll by. With this information (which can be derived by the event as well as the current state and props) we can derive the next active index.

So the solution was a concept I will be calling State Updaters, these are functions which can be (and often are) curried methods that lastly return a function that takes in state and props and returns some new state. They are curried because they need additional information, such as selectors and transformers to return the correct state.

Lets break down this step by step in some code.

class Counter extends React.Component {
  state = {
    count: this.props.defaultCount,
    propCount: this.props.count,
  };

  static getDerivedStateFromProps(nextProps, prevState) {
    /* we'll get to this later */
  }

  // This is used for local control flow
  // We determine if we call setState or not
  isControlled = () => typeof this.props.count !== "undefined";

  handleClick = (event) => {
    /* we'll get to this later */
  };

  render() {
    return (
      <Fragment>
        <button onClick={this.handleClick}>Increment Count</button>
        {this.state.count}
      </Fragment>
    );
  }
}

So we start off with some local state, a class method for handling the click event from the button, and an isControlled method for determining if an implementer is controlling the component or not.

The next step is to handle the click logic:

// ...
handleClick = (event) => {
  // If we aren't controlled (i.e. we manage our own state)
  // call setState with the return value of the state updater
  if (!this.isControlled()) {
    this.setState(stateUpdater());
  }
  // Always call the prop handleClick handler
  // first passing the event, and second passing an object
  // with a stateUpdater argument
  this.props.handleClick(event, {
    // defined in the module
    // could also be exported as well
    stateUpdater,
  });
};
// ...

Once we have the local handler resolved, now we can dive into the state updater method.

// return a function that accepts an object with three key fields
// 1. transformState: this determines if the returned state should be nested
// 2. selectState: this selects the correct UI component state within the parent state
// 3. fieldName: this is a string that is the key inside state that we update
export const stateUpdater =
  ({
    transformState = (state) => state,
    selectState = (state) => state,
    fieldName = "count",
  } = {}) =>
  // then return another function that accepts state and props
  (state, props) => {
    return transformState({
      ...selectState(state),
      [fieldName]: selectState(state)[fieldName] + 1,
    });
  };

Now that we know what the stateUpdater looks like, we can dive back into the event handler above. Inside the !this.isControlled() check, we setState using the returned function after calling stateUpdater with undefined (results in our default argument for transformState, selectState and fieldName).

There is one other thing we need to cover to fully make the UI component controllable:

class Counter extends React.Component {
  // ...
  state = {
    count: this.props.defaultCount,
    // this needs to be an exact reference to the value provided by props
    propCount: this.props.count,
  };

  static getDerivedStateFromProps(nextProps, prevState) {
    // if the exact comparison between propCount in local state
    // and the count provided by the props is false
    // then its time to update the component
    if (prevState.propCount !== nextProps.count) {
      return {
        count: nextProps.count,
        propCount: nextProps.count,
      };
    }
    return null;
  }
  // ...
}

Now we can put all this together into a working demo, which you can find here on Codesandbox.


Footnotes:

↩Back to reference

Most of the render prop code still lives in the carousel but it will most likely be removed before we open source.

↩Back to reference

Side note, I haven't even validated that this is what Downshift does, I have only some second hand knowledge of their helpers that they pass back up.


Tags:

ReactWeb DevelopmentComponents

Loading...

Related Posts

React

Multi-step Native HTML Forms

....

useInterval

....

Server Side Rendering Compatible CSS Theming

....

A quick tip to implementing CSS theming that's compatible with Server Side Rendered applications!

Resetting Controlled Components in Forms

....

A quick way to handle resetting internal state in components when a parent form is submitted!

Request for a (minimal) RSC Framework

....

Some features and functionality that I'd like within a React Server Component compatible framework.

Don't Break the Implicit Prop Contract

....

React components have a fundamental contract that is often unstated in their implementation, and you should know about it!

A Better useSSR Implementation

....

Replace that old useState and useEffect combo for a new and better option!

React Error Boundaries: Revisited

....

Revising my previous blog post on React Error Boundaries and my preferred go-to implementation!

Suspense Plus GraphQL

....

A few thoughts on using Suspense with GraphQL to optimize application data loading

Understanding React 16.3 Updates

....

A quick overview of the new lifecycle methods introduced in React 16.3

Web Development

Website Redesign v11

....

I've once again updated my personal website, this time powered by my own RSC framework and a custom CMS solution as well!

Onboarding Your New AI Teammate

....

Are we reinventing the wheel when it comes to onboarding new AI agents to a codebase, when we already have primitives available for onboarding humans?

Quick Tip - Theme Aware Images

....

Have you ever found the need to change the image you render on a web page based on the current preferred color scheme of your theme?

Async Class Creation In JavaScript

....

Have you ever wanted to create a class in JavaScript or TypeScript but also have the initialization be async? Here's a quick tip on a pattern that I've used in the past!

Website Redesign v10

....

I recently launched a rewrite and redesign of this personal website, I figured I'd talk a bit about the changes and new features that I added along the way!

Server Side Rendering Compatible CSS Theming

....

A quick tip to implementing CSS theming that's compatible with Server Side Rendered applications!

Podcasting By Hand

....

A brief overview on how we launched The Bikeshed Podcast, including a deep dive in our recording and distribution workflows!

Quick Tip - Specific Local Module Declarations

....

A quick tip outlining how to provide specific TypeScript type definitions for a local module!

On File-System Routing Conventions

....

Some rough thoughts on building a file-system routing based web application

You're Building Software Wrong

....

Slicing software: why vertical is better than horizontal.

Single File Web Apps

....

What if you could author an entire web application in a single file?

Resetting Controlled Components in Forms

....

A quick way to handle resetting internal state in components when a parent form is submitted!

A Quick Look at Import Maps

....

A brief look at Import Maps and package.json#imports to support isomorphic JavaScript applications!

Recommended Tech Talks

....

A collection of tech talks that I regularly re-watch and also recommend to everyone!

Request for a (minimal) RSC Framework

....

Some features and functionality that I'd like within a React Server Component compatible framework.

Bluesky Tips and Tools

....

A (running) collection of Bluesky tips, tools, packages, and other misc things!

The Bookkeeping Pattern

....

A quick look at a small but powerful pattern I've been leveraging as of late!

TSLite

....

A proposal for a minimal variant of TypeScript!

Monorepo Tips and Tricks

....

Sharing a few core recommendations when working within monorepos to make your life easier!

Next.js with Deno v2

....

This is a quick post noting that Next.js should now work with Deno v2!

Don't Break the Implicit Prop Contract

....

React components have a fundamental contract that is often unstated in their implementation, and you should know about it!

A Better useSSR Implementation

....

Replace that old useState and useEffect combo for a new and better option!

My Current Dev Setup

....

A quick look at the applications and tools that I (generally) use day to day for web development!

Abstract Your API

....

Proposing a solution for sharing core "business" logic across services!

Tip: Request and Response Headers

....

There's a common gotcha when creating Web Request and Response instances with Headers!

Using Feature Toggles to De-risk Refactors

....

Feature toggles are often underused by most software development teams, and yet offer so much value during not only feature development but also refactors

Hohoro

....

A quick introduction to my new side project, hohoro. An incremental JS/TS library build tool!

Custom Favicon Recipes

....

Two neat tricks for enhancing your site's favicon!

Corporate Sponsored OSS

....

The various risks and pitfalls of open source software run by corporations.

The Library-Docs Monorepo Template

....

A monorepo template for managing a library and documentation together.

Building Better Beacon

....

How we solved an almost show-stopping production bug, and how you can avoid it in your own projects.

Project Deep Dive: Tails

....

A(nother) deep dive into one of my recent side projects; tails - a plain and simple cocktail recipe app.

Churn Anxiety

....

When did semver major changes become so scary?

Service Monitors and Observability

....

Leveraging service monitors properly to improve service observability.

On Adopting CSS-in-JS

....

A brief recap of how Wayfair changed it's CSS approach not once but twice in the span of 5 years!

Project Deep Dive: Microfibre

....

A deep dive into one of my recent side projects; microfibre - a minimal text posting application

Pair Programming

....

Pair programming can be good sometimes - but not all the time

Suspense Plus GraphQL

....

A few thoughts on using Suspense with GraphQL to optimize application data loading

You've Launched, Now What?

....

A few thoughts on what to do after you launch a new project

Taking a Break

....

A few quick thoughts on burn out and taking a break

Understanding React 16.3 Updates

....

A quick overview of the new lifecycle methods introduced in React 16.3

CSS in JS

....

A few thoughts and patterns for using styled-jsx or other CSS-in-JS solutions

Redesign v6

....

A few thoughts on the redesign of my personal site, adopting Next.js and deploying via Now

JavaScript Weirdness

....

A few weird things about JavaScript

Calendar

....

Building a calendar web application