Skip to content

`shallowEqualExplain` function that returns an object explaining the difference (instead of the usual boolean). Useful for debugging React `PureComponent`s.

Notifications You must be signed in to change notification settings

OliverJAsh/shallow-equal-explain

Repository files navigation

shallow-equal-explain

This package provides a shallowEqualExplain function which is a copy of the shallowEqual function used by React's PureComponent, but instead of returning a boolean, it returns an object explaining the difference.

This is useful when you're trying to debug PureComponents, or any use of shallowEqual for that matter.

shallowEqualExplain has type:

function shallowEqualExplain<A, B>(objA: A, objB: B): Explanation;

Explanation is defined as:

type Explanation =
    | ObjectSame
    | ObjectDifferent
    | PropertiesSame
    | PropertiesDifferent;

ObjectDifferent and PropertiesDifferent provide further detail through their explanation properties, which have types ObjectDifferentExplanation and PropertiesExplanation respectively:

type ObjectDifferentExplanation = NotObjectOrNull | NonMatchingKeys;

type PropertyExplanation = Same | Different;
type PropertiesExplanation<Keys extends string> = {
    [key in Keys]: Same | Different
};

Example

t.deepEqual(
    shallowEqualExplain({ a: 1, b: 2, c: {} }, { a: 1, b: 2, c: {} }),
    Explanation.PropertiesDifferent({
        explanation: {
            a: PropertyExplanation.Same({}),
            b: PropertyExplanation.Same({}),
            c: PropertyExplanation.Different({}),
        },
    }),
);

Installation

yarn add shallow-equal-explain

Usage

import { shallowEqualExplain } from 'shallow-equal-explain';

shallowEqualExplain({ a: 1, b: 2, c: {} }, { a: 1, b: 2, c: {} });

With React:

class MyComponent extends React.PureComponent {
    componentDidUpdate(prevProps) {
        const currentProps = this.props;
        const shallowEqualExplanation = shallowEqualExplain(
            prevProps,
            currentProps,
        );

        console.log({ prevProps, currentProps, shallowEqualExplanation });
    }

    render() {
        return <div>My component</div>;
    }
}

See the tests for a full set of examples.

Development

yarn
npm run start

About

`shallowEqualExplain` function that returns an object explaining the difference (instead of the usual boolean). Useful for debugging React `PureComponent`s.

Resources

Stars

Watchers

Forks

Packages

No packages published