An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
May 21, 2022 06:57 pm GMT
Original Link: https://dev.to/subbiahc/solution-for-problem-with-usestate-and-eventhandlers-41e5
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:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To