react-use-trigger
TypeScript icon, indicating that this package has built-in type declarations

0.3.4 • Public • Published

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 />;
}

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.

Readme

Keywords

Package Sidebar

Install

npm i react-use-trigger

Weekly Downloads

1,351

Version

0.3.4

License

MIT

Unpacked Size

9.26 kB

Total Files

14

Last publish

Collaborators

  • ilyalesik