Home > front end >  how to use previousState in react hooks using typescript?
how to use previousState in react hooks using typescript?

Time:09-23

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

CodePudding user response:

The React ref should be typed to match exactly what it is storing. Typing prevCountRef as HTMLDivElement|null is incorrect. It should be number to match the count state type that you are caching in the ref. You can initialize the ref value to the initial state value as well to avoid any undefined or null typing.

Example:

const [count, setCount] = useState<number>(0);
const prevCountRef = useRef<number>(count);
useEffect(() => {
  prevCountRef.current = count;
}, [count]);
  • Related