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?

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]);

Leave a Reply