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

@shopify/react-hooks

v3.1.0

Published

A collection of primitive React hooks

Downloads

403,407

Readme

@shopify/react-hooks

Build Status Build Status License: MIT npm version npm bundle size (minified + gzip)

A collection of primitive React hooks.

Installation

yarn add @shopify/react-hooks

List of hooks

Usage

useDebouncedValue()

This hook provides a debounced value.

function MyComponent() {
  const [searchValue, setSearchValue] = useState('');
  const debouncedSearch = useDebouncedValue(searchValue);
  const {data, loading} = useQuery(SomeQuery, {
    variables: {
      query: debouncedSearch,
    },
  });

  function handleSearchTextChange(evt: React.KeyboardEvent) {
    setSearchValue(evt.currentTarget.value);
  }

  return <input onChange={handleSearchTextChange} />;
}

useDelayedCallback()

This hook provides a delayed callback function. It takes a callback and a delay in milliseconds. This might be useful when you want to invoke a callback after a certain delay.

function MyComponent() {
  const delay = 300;
  const callback = () => {
    console.log(
      `Oh, you KNOW I'm calling that callback after ${delay} milliseconds!`,
    );
  };

  const callbackWithDelay = useDelayedCallback(callback, delay);

  const onClick = () => {
    callbackWithDelay();
  };

  return <button onClick={onClick}>Click me!</button>;
}

useForceUpdate()

This hook provides a forceUpdate function which will force a component to re-render. This might be useful when you want to re-render after a mutable object gets updated.

const mutableObject = {foo: 'bar'};
export default function ResourceListFiltersExample() {
  const forceUpdate = useForceUpdate();
  const onClick = () => {
    mutableObject.foo = 'bar' + new Date().getTime();
    forceUpdate();
  };

  return <button onClick={onClick}>Click Me</button>;
}

useOnValueChange()

This hook tracks a given value and invokes a callback when it has changed.

function MyComponent({foo}: {foo: string}) {
  useOnValueChange(foo, (newValue, oldValue) => {
    console.log(`foo changed from ${oldValue} to ${newValue}`);
  });

  return null;
}

useTimeout()

This hook provides a declarative version of setTimeout(). The first argument is a callback that will be invoked after the given delay (number of milliseconds) as the second argument. Optionally, the timeout can be disabled by passing null as the delay.

function MyComponent() {
  const [status, setStatus] = React.useState('Pending');
  const pending = status === 'Pending';

  const buttonLabel = pending ? 'Cancel' : 'Reset';
  const handleClick = () => setStatus(pending ? 'Cancelled' : 'Pending');
  const delay = pending ? 1000 : null;

  useTimeout(() => setStatus('Fired'), delay);

  return (
    <div>
      <div>{status}</div>
      <button onClick={handleClick}>{buttonLabel}</button>
    </div>
  );
}

useInterval()

This hook provides a declarative version of setInterval. The first argument is a callback that will be invoked successively after the given delay (number of milliseconds) as the second argument. Optionally, the interval can be disabled by passing null as the delay.

function MyComponent() {
  const [counter, setCounter] = React.useState(0);
  const [enabled, setEnabled] = React.useState(true);

  const delay = enabled ? 1000 : null;
  const label = enabled ? 'Disable' : 'Enable';
  const toggle = () => setEnabled(!enabled);

  useInterval(() => setCounter(counter + 1), delay);

  return (
    <div>
      <div>{counter}</div>
      <button onClick={toggle}>{label}</button>
    </div>
  );
}

This is a TypeScript implementation of @gaeron's useInterval hook from the Overreacted blog post.

useIsomorphicLayoutEffect()

This hook is a drop-in replacement for useLayoutEffect that can be used safely in a server-side rendered app. It resolves to useEffect on the server and useLayoutEffect on the client (since useLayoutEffect cannot be used in a server-side environment).

Refer to the useLayoutEffect documentation to learn more.

useLazyRef()

This hook creates a ref object like React’s useRef, but instead of providing it the value directly, you provide a function that returns the value. The first time the hook is run, it will call the function and use the returned value as the initial ref.current value. Afterwards, the function is never invoked. You can use this for creating refs to values that are expensive to initialize.

function MyComponent() {
  const ref = useLazyRef(() => someExpensiveOperation());

  React.useEffect(() => {
    console.log('Initialized expensive ref', ref.current);
  });

  return null;
}

useMedia() & useMediaLayout()

This hook listens to a MediaQueryList created via matchMedia and returns true or false if it matches the media query string.

useMediaLayout is similar to useMedia but it uses useLayoutEffect internally to re-render synchronously.

function MyComponent() {
  const isSmallScreen = useMedia('(max-width: 640px)');
  return (
    <p>
      {isSmallScreen ? 'This is a small screen' : 'This is not a small screen'}
    </p>
  );
}

useMountedRef()

This hook keeps track of a component's mounted / un-mounted status and returns a ref object like React’s useRef with a boolean value representing said status. This is often used when a component contains an async task that sets state after the task has resolved.

import React from 'react';
import {useMountedRef} from '@shopify/react-hooks';

function MockComponent() {
  const [result, setResult] = React.useState();
  const mounted = useMountedRef();

  async function handleOnClick() {
    const result = await fetchData();

    if (mounted.current) {
      setData(result);
    }
  }

  return (
    <button onClick={handleOnClick} type="button">
      Fetch Data
    </button>
  );
}

usePrevious()

This hook stores the previous value of a given variable.

function Score({value}) {
  const previousValue = usePrevious(value);
  const newRecord = value > previousValue ? <p>We have a new record!</p> : null;

  return (
    <>
      <p>Current score: {value}</p>
      {newRecord}
    </>
  );
}

useToggle()

This hook provides an object that contains a boolean state value and a set of memoised callbacks to toggle it, force it to true, and force it to false. It accepts one argument that is the initial value of the state or an initializer function returning the initial value. This is useful for toggling the active state of modals and popovers.

function MyComponent() {
  const {
    value: isActive,
    toggle: toggleIsActive,
    setTrue: setIsActiveTrue,
    setFalse: setIsActiveFalse,
  } = useToggle(false);
  const activeText = isActive ? 'true' : 'false';

  return (
    <>
      <p>Value: {activeText}</p>
      <button onClick={toggleIsActive}>Toggle isActive state</button>
      <button onClick={setIsActiveTrue}>Set isActive state to true</button>
      <button onClick={setIsActiveFalse}>Set isActive state to false</button>
    </>
  );
}