use-custom-effect
Simple observer implementation based on React effect hook api, intended for building custom runtime effects.
Install
npm
npm install --save use-custom-effect
yarn
yarn add use-custom-effect
Demo
API
const useEffectSubscribe run = ;
-
useEffectSubscribe
- custom generated hook function based on similar API as React useEffect hook:;callback
- function that runs every time when custom effect is triggereddeps
- array of values referenced inside the effect callback function
-
run
- function that triggers the custom effect; every argument passed torun
function will be passed touseEffectSubscribe
callback
Usage
Basic example
;; ;
Fetch example
;; ; ; ;
Typescript
Typescript implementation just includes specifying custom effect callback type:
;
The benefits of using custom effects
-
Reducing props propagation.
You can resolve custom effect logic in the upper scope, and just delegate custom effect subscribe hook to the effect consumers. (There is no need to propagate props which take part into effect).
-
Controlling effect execution moment.
Via
useCustomHook
API, therun
function is at your disposal that executes all effect callbacks synchronously. -
Using custom effects as a composition unit.
You can use created custom effect hook to build more complex effects / UI behaviors.
License
MIT © radospavlicevic
This hook is created using create-react-hook.