@charlietango/use-lazy-ref

Create a new ref with lazy instantiated value.

Usage no npm install needed!

<script type="module">
  import charlietangoUseLazyRef from 'https://cdn.skypack.dev/@charlietango/use-lazy-ref';
</script>

README

useLazyRef

Create a new ref with lazy instantiated value.

Checkout the Storybook demo.

This is just a clean reusable helper hook for the common boilerplate:

const value = useRef()
if (!value.current) value.current = init()

Installation

yarn add @charlietango/use-lazy-ref

API

const result = useLazyRef(() => Result)

Once the value has been instantiated, you cannot reset it without recreating the component.

Example

A common use case is creating single instance objects, like the Apollo client. This ensures the client gets created during the first render, and reused in all the following calls.

import React from 'react'
import useLazyRef from '@charlietango/use-lazy-ref'
import { ApolloClient } from 'apollo-client'
import { ApolloProvider } from '@apollo/react-hooks'
import { createHttpLink } from 'apollo-link-http'

const Apollo = () => {
  const client = useLazyRef(
    () => new ApolloClient({ link: createHttpLink({ uri: '/graphql' }) }),
  )

  return <ApolloProvider client={client.current}>{children}</ApolloProvider>
}

export default Apollo