New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

react-usemountedstate

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-usemountedstate

Use state in asynchronous unmountable components without getting errors

  • 1.0.3
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
16
increased by77.78%
Maintainers
1
Weekly downloads
 
Created
Source

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.

Keywords

FAQs

Package last updated on 26 Aug 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc