README
React Memo
Heavily inspired by Reselect.
React Memo is a Higher Order Component wraps the your data derivation logic.
The main objective of this library was(is) to provide memoization logic for Material-UI's inline-styles. But it can also be used for any other class of calculations too.
To use this package you would need to be fairly familiar with React itself.
TL;DR
This is a simply a caching and cache invalidation library that works very well with react.
- Take data from prop and contex.
- Run value selectors and get needed values.
- Run resolver with the values if they are modified from the previous invocation. (resolver must be very cpu/memory intensive for this to have positive effect)
- Pass the results down as property.
- With each call to
componentWillReceiveProps
go to 1.
Installation
You can install this package with the following command:
npm install react-memo
Examples
These examples demonstrate how you can use this library:
Simple Usage
You can pass createWrapper a single property selector.
import React from 'react';
import {createSelector, createWrapper} from 'react-memo';
const TotalViewer = ({total}) => <span>{total}</span>;
// The first argument is the alias.
// The second is the array of value selectors.
// These must be pure and very fast.
// Re-evaluation is decided from changes to the returned
// value from these value selectors via ===.
// The last argument is the function that calculates the value
// of the property passed down. Which is called with the
// values returned from selectors in the same order.
// This is where the heavy calculations go.
const selector: any = createSelector('total', [
(props) => props.pocket,
(props) => props.bank,
], (pocket, bank) => /* Intense monetary calcuations */ pocket + bank);
const TotalViewerWrapper = createWrapper(selector)(TotalViewer);
const TotalMoneyIHave = (props) => <TotalViewerWrapper pocket={props.pocket} bank={0} />;
Complex Usage
You can pass createWrapper an array of property selectors and validators as options.
import React from 'react';
import {createSelector, createWrapper} from 'react-memo';
const TotalViewer = ({total, currencySymbol}) =>
<span>{total}{currencySymbol}</span>;
const totlaSelector: any = createSelector('total', [
(props) => props.pocket,
(props) => props.bank,
], (pocket, bank, currency) => pocket + bank);
// Value selectors are also passed context.
// However inorder to use context you must provide the contextTypes.
const currencySymbolSelector: any = createSelector('currencySymbol', [
(props, context) => context.currency,
], (currency) => currency ? currency : '