Language used: javascript with react
I have made a custom HOOK to keep the previous state
here my custom hooks
import { useEffect, useRef } from 'react';
export const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
};
here where I am using it :
export const ArticleQuantity = () => {
const [quantity, setQuantity] = useState(1);
const prevQuantity = usePrevious(quantity);
useEffect(() => {
console.log(prevQuantity quantity);
}, [quantity]);
<div>
<input
onChange={(e) => setQuantity(e.target.value)}
defaultValue={quantity}/>
<div>
}
Problem : if my user enter "3" in the input and then remove the "3" to enter "5", my previous state will be "null" because the last value is removed.
How can i keep "3" instead of null ?
Thank you.
CodePudding user response:
Add a condition to check null
useEffect(() => {
if(value){
ref.current = value;
}
}, [value]);