Convert Figma logo to code with AI

FormidableLabs logoreact-fast-compare

fastest deep equal comparison for React

1,584
54
1,584
11

Top Related Projects

The fastest deep equality check with Date, RegExp and ES6 Map, Set and typed arrays support

2,288

Write better assertions

Quick Overview

React-fast-compare is a lightweight JavaScript library for performing fast deep equality checks, particularly optimized for React applications. It offers a simple and efficient way to compare complex objects and arrays, making it useful for optimizing React component updates and memoization.

Pros

  • Extremely fast performance compared to other deep equality libraries
  • Small bundle size (less than 1KB gzipped)
  • Works with circular references and complex nested structures
  • Supports comparison of React elements and components

Cons

  • Limited to equality checks only; doesn't provide advanced comparison features
  • May not be necessary for simple comparisons where native JavaScript equality operators suffice
  • Doesn't support custom comparison logic for specific object types

Code Examples

  1. Basic usage for comparing objects:
import isEqual from 'react-fast-compare';

const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { a: 1, b: { c: 2 } };
const obj3 = { a: 1, b: { c: 3 } };

console.log(isEqual(obj1, obj2)); // true
console.log(isEqual(obj1, obj3)); // false
  1. Comparing arrays:
import isEqual from 'react-fast-compare';

const arr1 = [1, 2, [3, 4]];
const arr2 = [1, 2, [3, 4]];
const arr3 = [1, 2, [3, 5]];

console.log(isEqual(arr1, arr2)); // true
console.log(isEqual(arr1, arr3)); // false
  1. Using with React components:
import React, { memo } from 'react';
import isEqual from 'react-fast-compare';

const MyComponent = memo(({ data }) => {
  // Component logic here
}, isEqual);

export default MyComponent;

Getting Started

To use react-fast-compare in your project, follow these steps:

  1. Install the package:

    npm install react-fast-compare
    
  2. Import and use in your JavaScript/React code:

    import isEqual from 'react-fast-compare';
    
    // Use isEqual for deep comparisons
    if (isEqual(objA, objB)) {
      console.log('Objects are deeply equal');
    }
    

Competitor Comparisons

The fastest deep equality check with Date, RegExp and ES6 Map, Set and typed arrays support

Pros of fast-deep-equal

  • More versatile, supporting various data types beyond React-specific structures
  • Slightly faster performance in some scenarios
  • Smaller package size, beneficial for projects not using React

Cons of fast-deep-equal

  • Not optimized specifically for React components and props
  • May not handle certain React-specific cases as efficiently
  • Lacks some React-specific optimizations present in react-fast-compare

Code Comparison

react-fast-compare:

import compare from 'react-fast-compare';

const areEqual = compare(prevProps, nextProps);

fast-deep-equal:

import equal from 'fast-deep-equal';

const areEqual = equal(prevProps, nextProps);

Both libraries offer similar usage patterns, with the main difference being their internal implementations and optimizations.

react-fast-compare is tailored for React applications, providing optimizations for common React data structures and use cases. It's particularly efficient when comparing React props and state.

fast-deep-equal, on the other hand, is a more general-purpose deep equality comparison tool. It's not React-specific, making it suitable for a wider range of applications but potentially less optimized for React-specific scenarios.

Choose react-fast-compare for React-centric projects where performance in comparing React components is crucial. Opt for fast-deep-equal in non-React projects or when a more general-purpose deep equality comparison is needed.

2,288

Write better assertions

Pros of expect

  • More comprehensive testing framework with a wide range of matchers
  • Supports asynchronous testing and mocking
  • Integrates well with popular testing libraries like Jest

Cons of expect

  • Larger package size and potentially slower performance
  • More complex API compared to react-fast-compare
  • Not specifically optimized for React component comparisons

Code Comparison

expect:

expect(received).toEqual(expected);
expect(callback).toHaveBeenCalledTimes(2);
expect(asyncFunction()).resolves.toBe('result');

react-fast-compare:

import isEqual from 'react-fast-compare';

if (isEqual(objA, objB)) {
  console.log('Objects are equal');
}

Summary

expect is a full-featured testing framework with a wide range of capabilities, including asynchronous testing and mocking. It's well-suited for complex testing scenarios and integrates seamlessly with popular testing libraries.

react-fast-compare, on the other hand, is a lightweight and fast deep comparison utility specifically optimized for React applications. It focuses solely on comparing JavaScript objects and arrays, making it more efficient for tasks like prop comparison in React components.

Choose expect for comprehensive testing needs, and react-fast-compare for efficient object comparison in React applications.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

React Fast Compare — Formidable, We build the modern web

Downloads Bundle Size GH Actions Status Coverage Status npm version Maintenance Status

The fastest deep equal comparison for React. Very quick general-purpose deep comparison, too. Great for React.memo and shouldComponentUpdate.

This is a fork of the brilliant fast-deep-equal with some extra handling for React.

benchmark chart

(Check out the benchmarking details.)

Install

$ yarn add react-fast-compare
# or
$ npm install react-fast-compare

Highlights

  • ES5 compatible; works in node.js (0.10+) and browsers (IE9+)
  • deeply compares any value (besides objects with circular references)
  • handles React-specific circular references, like elements
  • checks equality Date and RegExp objects
  • should be as fast as fast-deep-equal via a single unified library, and with added guardrails for circular references.
  • small: under 660 bytes minified+gzipped

Usage

const isEqual = require("react-fast-compare");

// general usage
console.log(isEqual({ foo: "bar" }, { foo: "bar" })); // true

// React.memo
// only re-render ExpensiveComponent when the props have deeply changed
const DeepMemoComponent = React.memo(ExpensiveComponent, isEqual);

// React.Component shouldComponentUpdate
// only re-render AnotherExpensiveComponent when the props have deeply changed
class AnotherExpensiveComponent extends React.Component {
  shouldComponentUpdate(nextProps) {
    return !isEqual(this.props, nextProps);
  }
  render() {
    // ...
  }
}

Do I Need React.memo (or shouldComponentUpdate)?

What's faster than a really fast deep comparison? No deep comparison at all.

—This Readme

Deep checks in React.memo or a shouldComponentUpdate should not be used blindly. First, see if the default React.memo or PureComponent will work for you. If it won't (if you need deep checks), it's wise to make sure you've correctly indentified the bottleneck in your application by profiling the performance. After you've determined that you do need deep equality checks and you've identified the minimum number of places to apply them, then this library may be for you!

Benchmarking this Library

The absolute values are much less important than the relative differences between packages.

Benchmarking source can be found here. Each "operation" consists of running all relevant tests. The React benchmark uses both the generic tests and the react tests; these runs will be slower simply because there are more tests in each operation.

The results below are from a local test on a laptop (stats last updated 6/2/2020):

Generic Data

react-fast-compare x 177,600 ops/sec ±1.73% (92 runs sampled)
fast-deep-equal x 184,211 ops/sec ±0.65% (87 runs sampled)
lodash.isEqual x 39,826 ops/sec ±1.32% (86 runs sampled)
nano-equal x 176,023 ops/sec ±0.89% (92 runs sampled)
shallow-equal-fuzzy x 146,355 ops/sec ±0.64% (89 runs sampled)
  fastest: fast-deep-equal

react-fast-compare and fast-deep-equal should be the same speed for these tests; any difference is just noise. react-fast-compare won't be faster than fast-deep-equal, because it's based on it.

React and Generic Data

react-fast-compare x 86,392 ops/sec ±0.70% (93 runs sampled)
fast-deep-equal x 85,567 ops/sec ±0.95% (92 runs sampled)
lodash.isEqual x 7,369 ops/sec ±1.78% (84 runs sampled)
  fastest: react-fast-compare,fast-deep-equal

Two of these packages cannot handle comparing React elements, because they contain circular reference: nano-equal and shallow-equal-fuzzy.

Running Benchmarks

$ yarn install
$ yarn run benchmark

Differences between this library and fast-deep-equal

react-fast-compare is based on fast-deep-equal, with some additions:

  • react-fast-compare has try/catch guardrails for stack overflows from undetected (non-React) circular references.
  • react-fast-compare has a single unified entry point for all uses. No matter what your target application is, import equal from 'react-fast-compare' just works. fast-deep-equal has multiple entry points for different use cases.

This version of react-fast-compare tracks fast-deep-equal@3.1.1.

Bundle Size

There are a variety of ways to calculate bundle size for JavaScript code. You can see our size test code in the compress script in package.json. Bundlephobia's calculation is slightly higher, as they do not mangle during minification.

License

MIT

Contributing

Please see our contributions guide.

Maintenance Status

Active: Formidable is actively working on this project, and we expect to continue for work for the foreseeable future. Bug reports, feature requests and pull requests are welcome.

NPM DownloadsLast 30 Days