Debugging value changes in React’s shouldComponentUpdate()

TJ Holowaychuk
Mar 11, 2016 · 2 min read

React’s optional shouldComponentUpdate() lifecycle method can be used to improve performance by providing your own logic, but it can be a pain to debug if you’ve missed a comparison.

Typically with Redux and friends this means performing simple equality checks for the property values to allow renders on changes. Missing a property means you might be in for some fun hunting down which is missing! Here’s an example of what you might write:

This works just fine, but it can be easy to forget a property in larger components. Ideally you want something like:

A tiny ‘changed()’ utility function can do the dirty work and show us if anything has changed. (you’ll probably want to make that log output conditional ;p).

Usage looks like the following snippet, passing in the component name, props to check for changes, and both the old and new objects.

I haven’t bother making this a module yet since I think it can be done better, but I thought I’d share the tip in general. I’ve rigged mine to filter on localStorage.debugUpdates for now which accepts ‘*’ or a component name. You could also easily just assume all prop/state changes should cause a render.

I’m still a React noob so I’d love to hear if there’s a nicer solution out there!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store