react-usemountedstate

Use state in asynchronous unmountable components without getting errors


Keywords
React.js, useState, async, Promise, usePromise, usePromiseState, hook, mounted, components, mounted components, ES6, CommonJS
License
MIT
Install
npm install react-usemountedstate@1.0.3

Documentation

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.