Coder Social home page Coder Social logo

use-memo-one's Introduction

useMemoOne

useMemo and useCallback with a stable cache (semantic guarantee)

Build Status npm dependencies min minzip

Background

useMemo and useCallback cache the most recent result. However, this cache can be destroyed by React when it wants to:

You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance. - React docs

useMemoOne and useCallbackOne are concurrent mode safe alternatives to useMemo and useCallback that do provide semantic guarantee. What this means is that you will always get the same reference for a memoized value so long as there is no input change.

Using useMemoOne and useCallbackOne will consume more memory than useMemo and useCallback in order to provide a stable cache. React can release the cache of useMemo and useCallback, but useMemoOne will not release the cache until it is garbage collected.

Install

# npm
npm install use-memo-one --save
# yarn
yarn add use-memo-one

Usage

import { useMemoOne, useCallbackOne } from 'use-memo-one';

function App(props) {
  const { name, age } = props;
  const value = useMemoOne(() => ({ hello: name }), [name]);
  const getAge = useCallbackOne(() => age, [age]);

  // ...
}

Aliased imports

You can use this import style drop in replacement for useMemo and useCallback

This style also plays very well with eslint-plugin-react-hooks.

import { useMemo, useCallback } from 'use-memo-one';

⚠️ The aliased exports useMemo and useCallback will only work if you use only use-memo-one and will clash if you also use useMemo or useCallback from react

import { useMemo, useCallback } from 'react';
// ❌ naming clash
import { useMemo, useCallback } from 'use-memo-one';

API

See useMemo and useCallback

Linting

useMemo and useCallback have fantastic linting rules with auto fixing in the eslint-plugin-react-hooks package. In order to take advantage of these with useMemoOne and useCallbackOne, structure your import like this:

import { useMemo, useCallback } from 'use-memo-one';
// Or your can alias it yourself
import {
  useMemoOne as useMemo,
  useCallbackOne as useCallback,
} from 'use-memo-one';

function App() {
  const [isActive] = useState(false);

  const onClick = useCallback(() => {
    console.log('isActive', isActive);

    // the input array will now be correctly checked by eslint-plugin-react-hooks
  }, [isActive]);
}

eslint rules

Here are some eslint rules you are welcome to use

module.exports = {
  rules: {
    // ...other rules

    'no-restricted-imports': [
      'error',
      {
        // If you want to force an application to always use useMemoOne
        paths: [
          {
            name: 'react',
            importNames: ['useMemo', 'useCallback'],
            message:
              '`useMemo` and `useCallback` are subject to cache busting. Please use `useMemoOne`',
          },
          // If you want to force use of the aliased imports from useMemoOne
          {
            name: 'use-memo-one',
            importNames: ['useMemoOne', 'useCallbackOne'],
            message:
              'use-memo-one exports `useMemo` and `useCallback` which work nicer with `eslint-plugin-react-hooks`',
          },
        ],
      },
    ],
  },
};

use-memo-one's People

Contributors

alexreardon avatar denis-sokolov avatar framp avatar lourd avatar matt-oakes avatar orisomething avatar petecorreia avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

use-memo-one's Issues

TypeScript: Missing types for useCallback and useMemo

I am getting the error Module '"use-memo-one"' has no exported member 'useCallback' on a create-react-app project with TypeScript. This makes it impossible to use imports like this:

import { useCallback, useMemo } from 'use-memo-one'

As a workaround, I had to create an extra use-memo-one.d.ts file with:

declare module 'use-memo-one' {
	export const useMemo: typeof React.useMemo
	export const useCallback: typeof React.useCallback
}

Can you please update index.d.ts to include the useCallback and useMemo aliases?

Suggested additional eslint rule

May I suggest adding the following rule to the eslint recommendation to catch uses of React.useMemo and React.useCallback:

"no-restricted-properties": [
	2,
	{
		"object": "React",
		"property": "useMemo",
		"message": "Please use useMemo from 'use-memo-one'."
	},
	{
		"object": "React",
		"property": "useCallback",
		"message": "Please use useCallback from 'use-memo-one'."
	}
]

React 17 compatibility

Hi there,

would it be possible to add react 17 to peer dependencies? Do you see any possible drawback?

Thanks!

Why provide useCallbackOne?

useMemoOne is really handy! Thanks for making it! I just have a few questions about useCallbackOne: The React hooks API docs quoted in the readme specifically explain that useMemo should not be relied on for semantic guarantee, but I don't see anything like that for useCallback. Do you have additional info regarding this?

Also, since useMemoOne is intended to be used to create arbitrary values which are stable across re-renders, why provide useCallbackOne at all?

useCache or useLRU

Thanks for your insight into the issues with useMemo.

It would be good if there was a useCache or useLRU that could provide cached results for a given dependency input. This would work great with pure components that compute a pure output for a given input.

I have a set of transitions that move from A -> B -> C -> A. useMemo will recompute the value every time because properties change on each transition:

useMemo will only recompute the memoized value when one of the dependencies has changed.

Instead we want something that works as a simple hook and allows us to re-use the purely computed results from a set of dependency values. Like:

useCache will retain a cached value for each unique set of dependency values."

Feature request: `areInputsEqual` optional argument

Context
I'm trying to create a concurrent-mode-safe useShallowMemo hook. This hook would basically do this:

const memoizedObject = useMemo(() => ({ key1: val1, key2: val2 }), [val1, val2]);

but allow you to pass an arbitrary object as input (instead of having to manually split up and re-create the object like in the above example):

const memoizedObject = useShallowMemo({ key1: val1, key2: val2 });

This could be built on top of useMemoOne by converting the input object's keys/values into an input array to useMemoOne. However, we probably don't care about the order in the case of objects, so we'd have to sort the keys before creating this input array, which feels a little awkward.

Request
Add an optional third argument to useMemoOne, allowing us to provide a custom definition for areInputsEqual.

This would allow us to implement useShallowMemo very easily, like:

const useShallowMemo = (input) => useMemoOne(
  () => input,
  [input],
  ([a], [b]) => isShallowEqual(a, b),
);

where isShallowEqual does a shallow equality comparison on two objects.

Pull Request
I just created an issue to give some context and ask if it this feature would be welcome. If it is welcome, then I will create a pull request for it.

side effect in useMemoOne

https://codesandbox.io/s/condescending-poitras-zp2t7?file=/src/App.js

import React, { useState, useMemo } from "react";
import { useMemoOne } from "use-memo-one";
import "./styles.css";

export default function App() {
    const [state, setState] = useState(0);

    const [count, setCount] = useState(0);

    useMemoOne(() => {
        setState(count + 10);
    }, [count]);
    return (
        <div className="App">
            <h1>{count}</h1>
            <h2>{state}</h2>
            <button onClick={() => setCount((c) => c + 1)}>setCount</button>
        </div>
    );
}

If it has some side effect in useMemoOne, like set other state, it makes App re-render. And this useMemoOne will run again though count if not changed, which causes the infinite loop.

Use React.useMemo will be OK.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.