Page Menu
Home
c4science
Search
Configure Global Search
Log In
Files
F100871964
useUpdateImmediateEffect.js
No One
Temporary
Actions
Download File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Subscribers
None
File Metadata
Details
File Info
Storage
Attached
Created
Mon, Feb 3, 11:53
Size
1 KB
Mime Type
text/x-java
Expires
Wed, Feb 5, 11:53 (2 d)
Engine
blob
Format
Raw Data
Handle
24041723
Attached To
rOACCT Open Access Compliance Check Tool (OACCT)
useUpdateImmediateEffect.js
View Options
import { useRef } from 'react';
import useStableMemo from './useStableMemo';
import useWillUnmount from './useWillUnmount';
/**
* An _immediate_ effect that runs an effect callback when its dependency array
* changes. This is helpful for updates should must run during render, most
* commonly state derived from props; a more ergonomic version of https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops
*
* ```ts
* function Example({ value }) {
* const [intermediaryValue, setValue] = useState(value);
*
* useUpdateImmediateEffect(() => {
* setValue(value)
* }, [value])
* ```
*
* @category effects
*/
function useUpdateImmediateEffect(effect, deps) {
var firstRef = useRef(true);
var tearDown = useRef();
useWillUnmount(function () {
if (tearDown.current) tearDown.current();
});
useStableMemo(function () {
if (firstRef.current) {
firstRef.current = false;
return;
}
if (tearDown.current) tearDown.current();
tearDown.current = effect();
}, deps);
}
export default useUpdateImmediateEffect;
Event Timeline
Log In to Comment