Skip to content

Latest commit

 

History

History
90 lines (67 loc) · 2.16 KB

README.md

File metadata and controls

90 lines (67 loc) · 2.16 KB

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