https://github.com/sergiodxa/use-safe-callback
Wrap a function to ensure you never call it if a component is unmounted, useful to avoid cases where an async code could finish after a component has unmounted and it tries to update a state
https://github.com/sergiodxa/use-safe-callback
hooks react react-hooks react-state safe-callbacks
Last synced: 10 months ago
JSON representation
Wrap a function to ensure you never call it if a component is unmounted, useful to avoid cases where an async code could finish after a component has unmounted and it tries to update a state
- Host: GitHub
- URL: https://github.com/sergiodxa/use-safe-callback
- Owner: sergiodxa
- License: mit
- Created: 2020-07-23T06:31:22.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2023-01-07T20:23:01.000Z (about 3 years ago)
- Last Synced: 2025-03-28T20:46:09.125Z (11 months ago)
- Topics: hooks, react, react-hooks, react-state, safe-callbacks
- Language: TypeScript
- Homepage:
- Size: 1.18 MB
- Stars: 12
- Watchers: 1
- Forks: 1
- Open Issues: 14
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
# useSafeCallback  
Wrap a function to ensure you never call it if a component is unmounted, useful to avoid cases where an async code could finish after a component has unmounted and it tries to update a state.
## Usage
Install it
```sh
$ yarn add use-safe-callback
```
Import it
```ts
import useSafeCallback from "use-safe-callback"
```
Wrap your unsafe callback
```ts
const [state, unsafeDispatch] = React.useReducer(reducer, initialState);
const safeDispatch = useSafeCallback(unsafeDispatch);
```
Use it as your unsafe callback
```ts
safeDispatch({ type: "MY_ACTION" })
```
Your unsafe callback will not run if the component is unmounted, preventing you to trying to update the state.
## Author
- [Sergio XalambrÃ](https://sergiodxa.com)
Based on a [similar Hook](https://github.com/tannerlinsley/react-query/blob/2c49b5d29ccd9204bd7e30b23efd08224b0f7560/src/react/utils.js#L45-L57) by [Tanner Linsley](https://twitter.com/tannerlinsley).
## License
The MIT License.