react-stable-hooks
v1.0.1
Published
A set of React hooks to help prevent re-render loops and stabilize dependencies.
Maintainers
Readme
React Stable Hooks A collection of React hooks designed to help prevent common re-render loops and stabilize dependencies, improving your application's performance.
The Problem A common source of bugs and performance issues in React is the re-render loop. This often happens when using the useEffect hook with dependencies that are objects or arrays. Because JavaScript creates a new reference for objects and arrays on every render, useEffect's shallow comparison thinks the dependency has changed, causing the effect to run again, which might set state, causing another re-render, and so on.
// This component will log "Effect is running!" on every single render,
// even though the options object is structurally identical.
function MyComponent() {
const options = { enabled: true }; // New object on every render
useEffect(() => {
console.log('Effect is running!');
}, [options]); // options is always a new object, so this always runs
return My Component; }
The Solution This package provides custom hooks that give you more control over dependency comparison. The first hook in this collection is useDeepCompareEffect.
useDeepCompareEffect This hook works exactly like useEffect, but it performs a deep comparison on its dependency array instead of a shallow one. It will only re-run the effect if the actual values inside your dependency objects or arrays have changed.
import { useDeepCompareEffect } from '@your-username/react-stable-hooks';
function MyComponent() { const options = { enabled: true };
useDeepCompareEffect(() => {
// This will now only run when the value of options.enabled actually changes.
console.log('Effect is running!');
}, [options]);
return My Component; }
Installation npm install @your-username/react-stable-hooks
API useDeepCompareEffect(callback, dependencies) Parameters callback (required): The function to execute, just like in useEffect. It can optionally return a cleanup function.
dependencies (required): The dependency array. A deep comparison will be performed on this array to determine if the effect should re-run.
