All Projects → andywer → Use Inline Memo

andywer / Use Inline Memo

⚛️ React hook for memoizing values inline anywhere in a component

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Use Inline Memo

redis-memolock
Redis MemoLock - Distributed Caching with Promises
Stars: ✭ 63 (-58.55%)
Mutual labels:  memoization
Re Reselect
Enhance Reselect selectors with deeper memoization and cache management.
Stars: ✭ 932 (+513.16%)
Mutual labels:  memoization
Memery
A gem for memoization in Ruby
Stars: ✭ 98 (-35.53%)
Mutual labels:  memoization
invokable
Objects are functions! Treat any Object or Class as a Proc (like Enumerable but for Procs).
Stars: ✭ 40 (-73.68%)
Mutual labels:  memoization
Cached
Rust cache structures and easy function memoization
Stars: ✭ 530 (+248.68%)
Mutual labels:  memoization
Purefun
Functional Programming library for Java
Stars: ✭ 37 (-75.66%)
Mutual labels:  memoization
bash-cache
Transparent caching layer for bash functions; particularly useful for functions invoked as part of your prompt.
Stars: ✭ 45 (-70.39%)
Mutual labels:  memoization
Micro Memoize
A tiny, crazy fast memoization library for the 95% use-case
Stars: ✭ 135 (-11.18%)
Mutual labels:  memoization
Moize
The consistently-fast, complete memoization solution for JS
Stars: ✭ 628 (+313.16%)
Mutual labels:  memoization
Beautiful React Redux
Redux 🚀, Redux 🤘, Redux 🔥 - and the magic optimization
Stars: ✭ 87 (-42.76%)
Mutual labels:  memoization
Verge
🟣 Verge is a very tunable state-management engine on iOS App (UIKit / SwiftUI) and built-in ORM.
Stars: ✭ 273 (+79.61%)
Mutual labels:  memoization
Cachier
Persistent, stale-free, local and cross-machine caching for Python functions.
Stars: ✭ 359 (+136.18%)
Mutual labels:  memoization
Decko
💨 The 3 most useful ES7 decorators: bind, debounce and memoize
Stars: ✭ 1,024 (+573.68%)
Mutual labels:  memoization
cacheme-go
🚀 Schema based, typed Redis caching/memoize framework for Go
Stars: ✭ 19 (-87.5%)
Mutual labels:  memoization
Python Memoization
A powerful caching library for Python, with TTL support and multiple algorithm options.
Stars: ✭ 109 (-28.29%)
Mutual labels:  memoization
async-memo-ize
🛠 Memoize utility for async/await syntax and promises. It supports cache in memory or via Redis
Stars: ✭ 16 (-89.47%)
Mutual labels:  memoization
Immutable Tuple
Immutable finite list objects with constant-time equality testing (===) and no memory leaks.
Stars: ✭ 29 (-80.92%)
Mutual labels:  memoization
Data Structures
Common data structures and algorithms implemented in JavaScript
Stars: ✭ 139 (-8.55%)
Mutual labels:  memoization
Frontend Computer Science
A list of Computer Science topics important for a Front-End Developer to learn 📝
Stars: ✭ 113 (-25.66%)
Mutual labels:  memoization
React Selector Hooks
Collection of hook-based memoized selector factories for declarations outside of render.
Stars: ✭ 84 (-44.74%)
Mutual labels:  memoization

⚛︎ use-inline-memo

React hook for memoizing values and callbacks anywhere in a component.

Build status npm version


Like other hooks, you can call React.useMemo() and React.useCallback() only at the top of your component function and not use them conditionally.

Inline memos let us memoize anywhere without the restrictions that apply to the usage of hooks!

import { Button, TextField } from "@material-ui/core"
import React from "react"
import useInlineMemo from "use-inline-memo"

function NameForm(props) {
  const memo = useInlineMemo()
  const [newName, setNewName] = React.useState(props.prevName)

  // Conditional return prevents calling any hook after this line
  if (props.disabled) {
    return <div>(Disabled)</div>
  }

  return (
    <React.Fragment>
      <TextField
        label="Name"
        onChange={memo.nameChange(event => setNewName(event.target.value), [])}
        value={newName}
      />
      <Button
        onClick={memo.submitClick(() => props.onSubmit(newName), [newName])}
        style={memo.submitStyle({ margin: "16px auto 0" }, [])}
      >
        Submit
      </Button>
    </React.Fragment>
  )
}

Installation

npm install use-inline-memo

Usage

Everytime you want to memoize a value, call memo.X() with an identifier X of your choice. This identifier will be used to map the current call to values memoized in previous component renderings.

Calling useInlineMemo() without arguments should work in all ES2015+ runtimes as it requires the ES2015 Proxy. If you need to support older browsers like the Internet Explorer, you will have to state the memoization keys up-front:

function NameForm(props) {
  // Explicit keys to make it work in IE11
  const memo = useInlineMemo("nameChange", "submitClick", "submitStyle")
  const [newName, setNewName] = React.useState(props.prevName)

  return (
    <React.Fragment>
      <TextField
        label="Name"
        onChange={memo.nameChange(event => setNewName(event.target.value), [])}
        value={newName}
      />
      <Button
        onClick={memo.submitClick(() => props.onSubmit(newName), [newName])}
        style={memo.submitStyle({ margin: "16px auto 0" }, [])}
      >
        Submit
      </Button>
    </React.Fragment>
  )
}

When not run in production, there is also a check in place to prevent you from accidentally using the same identifier for two different values. Calling memo.X() with the same X twice during one rendering will lead to an error.

Use cases

Event listeners

Inline memoizers are perfect to define simple one-line callbacks in-place in the JSX without sacrificing performance.

// Before
function Component() {
  const [value, setValue] = React.useState("")
  const onUserInput = React.useCallback(
    (event: React.SyntheticEvent) => setValue(event.target.value),
    []
  )
  return (
    <input onChange={onUserInput} value={value} />
  )
}
// After
function Component() {
  const memo = useInlineMemo()
  const [value, setValue] = React.useState("")
  return (
    <input
      onChange={memo.textChange(event => setValue(event.target.value), [])}
      value={value}
    />
  )
}

style props & other objects

Using inline style props is oftentimes an express ticket to unnecessary re-renderings as you will create a new style object on each rendering, even though its content will in many cases never change.

// Before
function Component() {
  return (
    <Button style={{ color: "red" }} type="submit">
      Delete
    </Button>
  )
}
// After
function Component() {
  const memo = useInlineMemo()
  return (
    <Button style={memo.buttonStyle({ color: "red" }, [])} type="submit">
      Delete
    </Button>
  )
}

You don't need to memoize every style object of every single DOM element, though. Use it whenever you pass an object to a complex component which is expensive to re-render.

For more background information check out FAQs: Why memoize objects?.

API

useInlineMemo(): MemoFunction

Call it once in a component to obtain the memo object carrying the memoization functions.

useInlineMemo(...keys: string[]): MemoFunction

State the memoization keys explicitly if you need to support Internet Explorer where Proxy is not available.

memo[id: string](value: T, deps: any[]): T

Works the same as a call to React.useMemo() or React.useCallback(), only without the wrapping callback function. That wrapping function is useful to run expensive instantiations only if we actually refresh the value, but for our use case this is rather unlikely, so we provide you with a more convenient API instead.

id is used to map different memoization calls between component renderings.

FAQs

How does that work?

The reason why React hooks cannot be called arbitrarily is that React needs to match the current hook call to previous calls. The only way it can match them is by assuming that the same hooks will always be called in the same order.

So what we do here is to provide a hook useInlineMemo() that creates a Map to match memo.X() calls to the memoized value and the deps array. We can match calls to memo.X() between different re-renderings by using X as an identifier.

Why is memoization so important?

To ensure good performance you want to re-render as few components as possible if some application state changes. In React we use React.memo() for that which judges by comparing the current component props to the props of the previous rendering.

Without memoization we will very often create the same objects, callbacks, ... with the same content over and over again for each rendering, but as they are new instances every time, they will not be recognized as the same values and cause unnecessary re-renderings (see "Why memoize objects?" below).

Why memoize objects?

When React.memo() determines whether a component needs to be re-rendered, it tests if the property values are equivalent to the property values of the last rendering. It does though by comparing them for equality by reference, as anything else would take too much time.

Now if the parent component creates a new object and passes it to the component as a property, React will only check if the object is exactly the same object instance as for the last rendering (newObject === prevObject). Even if the object has exactly the same properties as before, with the exact same values, it will nevertheless be a new object that just happens to have the same content.

Without memoization React.memo() will always re-render the component as we keep passing new object instances – the equality comparison of the old and the new property value will never be true. Memoization makes sure to re-use the actual last object instance, thus skipping re-rendering.

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].