useeffectonupdate
v1.0.1
Published
A custom React hook to run an effect only on updates, not on initial mount.
Maintainers
Readme
useEffectOnUpdate
Description
useEffectOnUpdate is a custom React hook designed to run side effects only on component updates, avoiding execution on the initial mount. This addresses a common issue with React's native useEffect hook, where effects are run after every render, including the first mount. This behavior often leads to performance issues or unintended side effects when dependencies change.
Problem
The standard React useEffect hook triggers both after the initial mount and after every subsequent update if the dependencies change. This default behavior can lead to unnecessary computations and side effects on mount, which might not always be desired. For example, you might want to make an API call only when specific props change, but not right when the component mounts.
Solution
useEffectOnUpdate provides a simple and efficient solution to run effects only on updates. By skipping the initial invocation, this hook helps in optimizing component behavior and performance, focusing effect logic strictly on dependency changes after the component has mounted.
Installation
Install the package using npm:
npm install useeffectonupdateOr using Yarn
yarn add useeffectonupdateUsage
To use useeffectonupdate, import it in your React component and specify your effect function along with dependencies:
import { useEffectOnUpdate } from 'useeffectonupdate';
function MyComponent(props) {
useEffectOnUpdate(() => {
// Your effect logic here, which will run only on updates
console.log('Component updated with props:', props);
}, [props]);
}
export default MyComponent;API
useEffectOnUpdate(effect, dependencies)
effect: A function containing the side-effect logic.dependencies: An array of dependencies which, when changed, will trigger the effect.
License
This project is licensed under the MIT License - see the License file for details
