react-usemountedstate
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

useMountedState

NPM version License

A React.js hook to use the official useState hook on super-duper complicated components with a lot asynchronous setStates that might be executed, when a component might be already unmounted.

Install with npm:

# via npm
npm install react-usemountedstate

# via yarn
yarn add react-usemountedstate

Usage

The useMountedState function takes no arguments, it creates the slightly special useState hook. It returns a function, that is supposed to be used instead of the original useState. Otherwise the useState usage remains the same.

import React, {useState as useReactState} from 'react';
import useMountedState from 'react-usemountedstate';


// use in Component
function App(props) {
	const [showComp, setShowComp] = useReactState(true);


	React.useEffect(() => {
		setTimeout(() => {
			setShowComp(false);
		}, 3000);
	}, []);


	return (<>
		{showComp && <Comp />}
	</>);
};

function Comp(props) {
	const useState = useMountedState();								// Create useState hook -> instead of the original React.useState

	const [somestate, setSomestate] = useState('initial value');	// Use the new hook as usual! Just like React.useState


	React.useEffect(() => {
		setTimeout(() => {
			setSomestate('Other value!');							// That should not be done!!! It should be cleaned up properly!
		}, 6000);
	}, []);


	return (<div>
		{somestate}
	</div>);
};

License

MIT Copyright (c) 2020 Nikita 'donnikitos' Nitichevski.

Package Sidebar

Install

npm i react-usemountedstate

Weekly Downloads

8

Version

1.0.3

License

MIT

Unpacked Size

4.2 kB

Total Files

4

Last publish

Collaborators

  • donnikitos