Debugging value changes in React’s shouldComponentUpdate()
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!