useLatestValue
Importing useLatestValue Hook​
import { useLatestValue } from '@ciceksepeti/cui-hooks';
Example​
import React, { useRef, useState } from 'react';
import { useLatestValue } from '@ciceksepeti/cui-hooks';
const LatestValue = () => {
const [text, setText] = useState('This text will change');
const ref = useRef(null);
const latest = useLatestValue(ref);
const onChangeHandler = () => {
const { value } = latest.current.current;
setText(value);
};
return (
<div>
<input
type="text"
ref={ref}
onChange={onChangeHandler}
placeholder="Please type here..."
/>
<p>{text}</p>
</div>
);
};
export default LatestValue;
Preview & Test​
PREVIEW & TEST AREA
useLatestValue
Stores latest value with ref
Useful to get access to the latest value of some props or state inside an async callback, instead of at the time the callback was created.
Example: This text will change