@freckle/react-hooks
TypeScript icon, indicating that this package has built-in type declarations

5.2.1 • Public • Published

@freckle/react-hooks

Provides a collection of React hooks.

The key to this collection of hooks is the useExtraDeps hook. This hook avoids the pitfalls of using objects and arrays as dependencies for React's built-in useEffect hook. The other hooks are implemented in terms of useExtraDeps. Please see the documentation for useExtraDeps for further details.

Collection

This package provides (in no particular order) the following React hooks:

  1. useSafeEffect / useSafeEffectExtraDeps
  2. useSafeCallback / useSafeCallbackExtraDeps
  3. usePrevious
  4. useExtraDeps

Usage

Example usage of an object as a dependency:

import { useSafeEffectExtraDeps } from "@freckle/react-hooks";
import { useSelector, useDispatch } from "react-redux";

export function StoreContainer(props: { color: Color }): React.Node {
  const dispatch = useDispatch();

  const { isLoading, itemsData, error } = useSelector(
    (state) => state.storeReducer
  );

  useSafeEffectExtraDeps(
    ({ color }) => {
      dispatch(loadItems(color));
    },
    [dispatch],
    {
      color: {
        value: props.color,
        comparator: (color1, color2) => color1.id === color2.id,
      },
    }
  );

  return <PiggyStore items={itemsData || []} error={error} />;
}

For simpler use cases, we can avoid the extraDeps bit:

import {useSafeEffect} from '@freckle/react-hooks'
import {useSelector, useDispatch} from 'react-redux'

export function StoreContainer(): React.Node {
  const dispatch = useDispatch()

  const {isLoading, itemsData, error} = useSelector(
    state => state.storeReducer
  )

  useSafeEffect(() => {
    dispatch(loadItems())
  }, [dispatch])

  return (
    <PiggyStore items={itemsData || []} error={error} />
  )
}

Readme

Keywords

none

Package Sidebar

Install

npm i @freckle/react-hooks

Weekly Downloads

183

Version

5.2.1

License

MIT

Unpacked Size

66.9 kB

Total Files

50

Last publish

Collaborators

  • luckysoni
  • z0isch
  • stackptr
  • carlos-cubas
  • freckle-engineering