Skip to content

ilyalesik/react-use-trigger

Repository files navigation

react-use-trigger

Build Status npm version

React Hook for trigger effect from any place of code. It is an implementation a Pub-Sub strategy on React Hooks.

  • Small 305 bytes (minified and gzipped).
  • Both Flow and TS types included.
import createTrigger from "react-use-trigger";
import useTriggerEffect from "react-use-trigger/useTriggerEffect";

const fooTrigger = createTrigger();

export const Subscriber = () => {  
    useTriggerEffect(() => {
        // make some effect
    }, fooTrigger);
  
    return <div />;
}

export const Sender = () => { 
    return <button onClick={() => {
        fooTrigger() // call trigger
    }}>Send</button>
}

Also, useTrigger may be used for combine with other inputs:

export const Subscriber = (props) => {  
    const fooTriggerValue = useTrigger(fooTrigger);
    const [someState, setSomeState] = useState();
    
    useEffect(() => {
        // make some effect
    }, [fooTriggerValue, props.someProp, someState]);
  
    return <div />;
}
Sponsored by Lessmess

Installation

Install it with yarn:

yarn add react-use-trigger

Or with npm:

npm i react-use-trigger --save

API

createTrigger(): TriggerWrapper;

Create a trigger. TriggerWrapper is function, that update value of trigger.

useTrigger(triggerWrapper: TriggerWrapper): string;

Returns current value of trigger. A string, generated by nanoid.

Can be used for combine trigger with other inputs:

import useTrigger from "react-use-trigger/useTrigger";

export const Subscriber = (props) => {  
    const fooTriggerValue = useTrigger(fooTrigger);
    const [someState, setSomeState] = useState();
    
    useEffect(() => {
        // make some effect
    }, [fooTriggerValue, props.someProp, someState]);
  
    return <div />;
}

useTriggerEffect(create: () => MaybeCleanUpFn, triggerWrapper: TriggerWrapper): void;

Call effect (from create) for every change of trigger.