Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to keep the previous value if not NULL

Language used: javascript with react

I have made a custom HOOK to keep the previous state

here my custom hooks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

Add a condition to check null

  useEffect(() => {
    if(value){ 
      ref.current = value;
    }
  }, [value]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading