https://github.com/davidhu2000/use-better-effect
A wrapper around `React.useEffect` but with improved API
https://github.com/davidhu2000/use-better-effect
react react-hooks react-native reactjs useeffect useeffect-hook useeffects
Last synced: 19 days ago
JSON representation
A wrapper around `React.useEffect` but with improved API
- Host: GitHub
- URL: https://github.com/davidhu2000/use-better-effect
- Owner: davidhu2000
- License: mit
- Created: 2022-12-13T06:55:08.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2022-12-15T23:24:07.000Z (about 3 years ago)
- Last Synced: 2025-11-04T17:20:37.207Z (3 months ago)
- Topics: react, react-hooks, react-native, reactjs, useeffect, useeffect-hook, useeffects
- Language: TypeScript
- Homepage:
- Size: 35.5 MB
- Stars: 3
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# useBetterEffect
[][npm_url]
[][npm_url]


[](https://coveralls.io/github/davidhu2000/use-better-effect?branch=main)



[npm_url]: https://www.npmjs.org/package/use-better-effect
A wrapper around `React.useEffect` but with improved API
## Installation
With Yarn:
```bash
yarn add use-better-effect
```
With npm:
```bash
npm install --save use-better-effect
```
## Background
`useEffect` is a powerful tool but the API has some gotchas. See the following examples:
```ts
// someFn runs on every render
useEffect(() => {
someFn();
});
// someFn only run on mount
useEffect(() => {
someFn();
}, []);
// someFn rerun when a or b changes
useEffect(() => {
someFn();
}, [a, b]);
// the returned function is called on unmount
useEffect(() => {
someFn();
return () => anotherFn();
}, [a, b]);
```
These implicit behaviors are hard to understand by just looking at the code.
## Improved API
`useBetterEffect` uses typescript function overloading to improve the developer experience when using the effect for different conditions. There are 3 supports run conditions:
- ON_MOUNT
- EVERY_RENDER
- DEPENDENCIES_CHANGED
For `ON_MOUNT` and `EVERY_RENDER`, passing in dependencies will result in a type error and `useBetterEffect` auto computes the dependency argument as `[]` and `undefined` respectively.
The cleanup function is passing as an explict optional arugment.
## Examples
```ts
import { useBetterEffect } from "use-better-effect";
useBetterEffect({
callbackFn: () => console.log("yay better"),
cleanupFn: () => console.log("so fresh and so clean"),
runCondition: "ON_MOUNT",
});
useBetterEffect({
callbackFn: () => console.log("yay better"),
cleanupFn: () => console.log("so fresh and so clean"),
runCondition: "EVERY_RENDER",
});
useBetterEffect({
callbackFn: () => console.log("yay better"),
cleanupFn: () => console.log("so fresh and so clean"),
runCondition: "DEPENDENCIES_CHANGED",
dependencies: [count],
});
```