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

Understanding React 16.3 Updates

Published ....
Last modified ....

Share this post on BlueskySee discussion on Bluesky


If you are a frontend engineer working with view libraries than you have most likely heard about the recent React updates launched with 16.3.0 (and 16.3.1). I have been using some of these features for a bit, and noticed some interesting patterns that begin to appear, and some pitfalls that many developers might fall into when migrating components and whole applications to use the new 16.3 features.

Context

I could write a full blog post about the new context api in React 16.3, however I want to keep the post relatively short and to the point.

A few of the patterns I have noticed with the new context api are:

Providing a default context can be useful.

If you build UI components for use across a larger application, its unreasonable to require all of the other react components using your components to also wrap your component in a provider. A powerful feature of the new context api is being able to define an initial context value for the consumers. This value will be used when your context consuming component is rendered in a component tree without a provider parent.

import React, { createContext }





















from
"
react
"
;
const { Provider, Consumer } = createContext({
theme: {
light: "#f8f9f9",
dark: "#374047",
},
});
const UIComponent = (props) => (
<Consumer>
{({ theme }) => (
<button
style={{
color: theme.light,
background: theme.dark,
}}
>
Button
</button>
)}
</Consumer>
);

A minor performance improvement for context provider wrappers is to use a key from state as the context provided

If you want to wrap your context provider in some wrapper that provides an update method of some sort, you generally will do something like this:

export default class ContextProvider extends Component {
  state = {
    light: "#f8f9f9",
    dark: "#374047",
  };
  updateTheme = (args) => {
    /* Implementation detail */
  };
  render() {
    return (
      <Provider
        // ⚠️⚠️⚠️⚠️
        value={{
          ...this.state,
          updateTheme: this.updateTheme,
        }}
      >
        {this.props.children}
      </Provider>
    );
  }
}

However! This will potentially cause unnecessary re-renders, as now the value provided to the consumers will always be a new object!!!

A simple way to get around this is to construct a nested object in state that is the context you want to provide:

export default class ContextProvider extends Component {
  /* Note this needs to be defined before state below */
  updateTheme = (args) => {
    /* Implementation detail */
  };
  state = {
    light: "#f8f9f9",
    dark: "#374047",
    context: {
      light: "#f8f9f9",
      dark: "#374047",
      updateTheme: this.updateTheme,
    },
  };
  render() {
    return <Provider value={this.state.context}>{this.props.children}</Provider>;
  }
}

getDerivedStateFromProps

So far I have noticed three primary pitfalls of the new static getDerivedStateFromProps lifecycle method on React components.

Always return a value at the end of the getDerivedStateFromProps method.

React will ensure to warn you if you ever return undefined (which will be the return value if you don't actively return anything) from the method. A good example of when this might happen is like this:

class App extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.value !== prevState.value) {
      return {
        value: nextProps.value,
      };
    }
    // ⚠️⚠️⚠️⚠️
  }

  /* implementation detail */
}

Note that if nextProps.value does equal prevState.value then the method will return undefined.

One tip I suggest to resolve this potential issue is to start by adding one last return null at the end of the method when you first add getDerivedStateFromProps:

class App extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.value !== prevState.value) {
      return {
        value: nextProps.value,
      };
    }
    // Start by adding this, then modify the logic above
    return null;
  }

  /* implementation detail */
}

getDerivedStateFromProps will overwrite any initial state if you conditionally fall back to default values

This was a difficult one to debug, but one key thing to keep in mind when using getDerivedStateFromProps is that it will run before the first-ever render. This can lead to some issues with colliding values between the return of this method and your component's initial state, for example:

class App extends Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.value !== prevState.value) {
      return {
        value: nextProps.value,
      };
    }
    return null;
  }

  state = {
    // ⚠️⚠️⚠️⚠️
    value: this.props.value || 0,
  };

  /* implementation detail */
}

In the above snippet, if this.props.value is null or undefined initially, then many would think that the value of this.state.value on the initial render will be 0, unfortunately because of getDerivedStateFromProps, this.state.value will be this.props.value always and will never be the fallback of 0.

So far the only way I found to get around this is to either track if it is the first time calling getDerivedStateFromProps, or to check that nextProps.value is neither null or undefined before the !== comparison.

  1. If you need to compare to prevProps you need to store that information in state

This is kind of the largest discussion about this new feature, many developers have voiced their opinions in adding prevProps as another argument to the method to compare new props with the previous props. The only way to get around this is to store the needed information from prevProps into state:

class App extends Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    const { prevProps } = prevState;
    if (nextProps.value !== prevProps.value) {
      return {
        prevProps: nextProps,
        someDerivedValue: nextProps.value,
      };
    }
    return null;
  }

  state = {
    prevProps: this.props,
    someDerivedValue: 0,
  };
}

getSnapshotBeforeUpdate

Coming soon, I haven't written too many components that need this just yet. But I have a feeling I will be using this a decent amount!


Tags:

ReactJavaScriptWeb Development

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

Managing Complex UI Component State

....

A few thoughts on managing complex UI component state within React

JavaScript

Progressive Identifiers

....

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!

The Bookkeeping Pattern

....

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

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

....

TSLite

....

A proposal for a minimal variant of TypeScript!

CSS in JS

....

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

JavaScript Weirdness

....

A few weird things about JavaScript

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

Managing Complex UI Component State

....

A few thoughts on managing complex UI component state within React

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