Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 21, 2022 06:57 pm GMT

Solution for problem with useState and eventHandlers

import { useEffect } from "react";import { useRefState } from "utils";export default function HomePage() {  const [mouseDownCounter, setMouseDownCounter] = useRefState(0);  useEffect(() => {    window.addEventListener("mousedown", () => {      setMouseDownCounter(mouseDownCounter + 1);    });  }, []);  return <div>{mouseDownCounter}</div>;}

With react functional programing we got a problem of accessing latest react state inside addEventListener. mouseDownCounter value will always to 0 inside addEventListener callback function, this can be solved by creating a custom hook that uses ref to store the state. Solution below.

import { useEffect } from "react";import { useRefState } from "utils";export default function HomePage() {  const [    mouseDownCounter,    setMouseDownCounter,    getMouseDownCounter,  ] = useRefState(0);  useEffect(() => {    window.addEventListener("mousedown", () => {      setMouseDownCounter(getMouseDownCounter() + 1);    });  }, []);  return <div>{mouseDownCounter}</div>;}

useRefState is same as useState, but has third parameter that exposes the current value of the state. To expose the current state we use react ref. Code below.

/** * same as use state, but we get a third param to get current value. This will be useful while working with settimeout, eventHandlers, promises and axios api calls. */export function useRefState<T>(  defaultValue: T): [T, (updatedValue: T) => void, () => T] {  const ref = useRef(defaultValue);  const [state, setState] = useState(defaultValue);  function setStateFn(updatedValue: any) {    ref.current = updatedValue;    setState(updatedValue);  }  function getValueFn() {    return ref.current;  }  return [state, setStateFn, getValueFn];}

Original Link: https://dev.to/subbiahc/solution-for-problem-with-usestate-and-eventhandlers-41e5

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To