Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Component-based disposal for React

License

NotificationsYou must be signed in to change notification settings

lxsmnsyc/use-dispose

Repository files navigation

React hook for running dispose logic for cancelled components.

NPMJavaScript Style Guide

Usage

Install

yarn add use-dispose

Why?

In Strict mode and Concurrent mode, components may render twice before commit to catch and prevent render-time side-effects. However, since the side-effects scheduled foruseLayoutEffect anduseEffect are never called on the first render, there could be unintended leaks like double event registrations from external sources.

useDispose attempts to solve this issue by running a registered cleanup for cancelled components, this helps clean and manage leaks that happened on the render phases.useDispose only runs for cancelled components and not for components that runs their side-effects successfully.

import{useDispose}from'use-dispose';// Creates an object with a cleanup logic inside it.// React may create two instances during Strict and Concurrent Mode// which can lead to undisposed instances like subscriptions.const[state]=useState(()=>newDisposableObject());// useDispose guarantees that the object gets disposed when// the component is cancelled.useDispose(()=>{state.dispose();});// If you want to run disposal only on initial render phase// You may add "true" as a second argument which toggles// initial render only cleanup.useDispose(()=>{state.dispose();},true);

There's also theuseDisposableMemo where the produced object from the memoization process which automatically gets disposed when a new object is produced, the component is cancelled or when the component unmounts:

import{useDisposableMemo}from'use-dispose';// Create a disposable object that is automatically disposed// on recomputation and on component cancellation/unmount.constdisposableObject=useDisposableMemo(()=>newDisposableObject(deps1,deps2),(object)=>object.dispose(),[deps1,deps2],);

Dispose timeouts

useDispose anduseDisposableMemo schedules the dispose callback 5 seconds after the render method is run. You may change this throughsetDisposeTimeout.

License

MIT ©lxsmnsyc


[8]ページ先頭

©2009-2025 Movatter.jp