react-use-trigger

React effect trigger hook

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
react-use-trigger
0.3.45 years ago5 years agoMinified + gzip package size for react-use-trigger in KB

Readme

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](https://github.com/ai/nanoid).

Can be used for combine trigger with other inputs:
```javascript
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.