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 use previousState in react hooks using typescript?

I trying to understand how to understand how to use previous state using react hooks in typescript.

The code below works, but you will have to ignore the error which is: Type 'number' is not assignable to type 'HTMLDivElement'.

Yes, that makes sense as you can’t cast number to HTMLDivElement, but what is the right way to implement previous state in react 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

Eventually I would like to use it in DetailsList (fluentui) to handle items when they are deleted.

import { useEffect, useRef, useState } from "react";

  export function Counter() {
    const [count, setCount] = useState(0);
    const prevCountRef = useRef<HTMLDivElement|null>(null);
    useEffect(() => {
      prevCountRef.current = count;
    }, [count]);
    return (
      <h1>
        Now: {count}, before: {prevCountRef.current}

        <button onClick={() => setCount((count) => count + 1)}>Increment</button>
      </h1>
    );
  }

>Solution :

It’s not evident at all why you typed the prevCountRef as HTMLDivElement|null. It should be number to match the count state type that you are caching in the ref.

Example:

const [count, setCount] = useState<number>(0);
const prevCountRef = useRef<number>(count);
useEffect(() => {
  prevCountRef.current = count;
}, [count]);
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