Macil / use-kefir

React hook for allowing components to receive values from a Kefir Observable
MIT License
0 stars 0 forks source link

use-kefir

GitHub license npm version Circle CI Greenkeeper badge

This is a React hook for allowing components to subscribe to a Kefir observable and read the latest value from it.

Example

import { useKefir } from 'use-kefir';

function MyComponent(props) {
  const { model } = props;

  const name = useKefir(
    model
      .getChangesStream() // some kefir stream
      .toProperty(() => null)
      .map(() => model.get('name')),
    model.get('name'),
    [model]
  );

  return <div>{name}</div>;
}

API

useKefir

export function useKefir(stream, initialValue, inputs)

This function is a React hook that may only be called from a functional React component. On first render, it returns the initialValue (if initialValue is a function, then the function is called and its return value is used). After the component is mounted and committed to the screen, the stream is subscribed to. Whenever stream emits a new value, the React component will re-render, and useKefir will return the latest value received from the stream.

useSyncKefir

export function useSyncKefir(stream, initialValue, inputs)

Works just like useKefir, but subscribes to stream before the initial render is committed to the screen. Internally it uses React's useLayoutEffect hook, unlike useKefir which uses React's useEffect hook. The useKefir function should be preferred unless this difference is critical in a component's specific use case. React's useLayoutEffect and therefore useSyncKefir are not allowed to be used in React components that are rendered server-side.

Types

Both TypeScript and Flow type definitions for this module are included! The type definitions won't require any configuration to use.