npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-inline-memo

v0.2.0

Published

React hook for memoizing values inline in JSX.

Downloads

257

Readme

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

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.

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).

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