Using useRef
to keep track of the latest state value while avoiding stale closures is a common pattern in React. Your example demonstrates this well. Here’s a breakdown of how it works:
- State Management: You maintain the
count
state usinguseState
. - Reference for Latest Value: You create a
countRef
usinguseRef
, which will hold the latest value ofcount
. - Updating the Ref: Inside the first
useEffect
, you updatecountRef.current
every timecount
changes. This ensures thatcountRef
always holds the most recent value ofcount
. - Setting Up the Timer: The second
useEffect
sets up a timer usingsetInterval
to increment the count every second. - Using the Latest Count in Timeout: When the 10-second timer triggers, it accesses
countRef.current
to log the latest count, which avoids the stale closure problem. - Cleanup: Finally, you clear the interval and timeout in the cleanup function.
Here’s the code with minor functionality for clarity:
#react #javascript
import React, { useState, useEffect, useRef } from 'react';
function Counter() {
const [count, setCount] = useState(1);
const countRef = useRef(count);
useEffect(() => {
countRef.current = count; // Update the ref whenever count changes
}, [count]);
useEffect(() => {
const interval = setInterval(() => {
setCount(prevCount => prevCount + 1);
}, 1000); // Increment count every 1 second
const timeout = setTimeout(() => {
console.log(`Count after 10 seconds: ${countRef.current}`);
}, 10000); // Log count after 10 seconds
return () => {
clearInterval(interval);
clearTimeout(timeout);
};
}, []); // Run once on mount
return <span>{count}</span>;
}
export default Counter;
Note:
useRef
is effectively used to maintain a reference to the latestcount
value without causing re-renders.- This pattern is commonly referred to as “useLatest” in various libraries and is quite useful for cases like timers or asynchronous operations where you need the most recent state.
This approach ensures you are always working with the most recent state.
Best Practices for Implementing Coding Filters!
To get the most out of coding filters, it’s essential to follow best practices when implementing them. This includes writing reusable filter functions, keeping logic modular, and ensuring that filters are applied consistently throughout your codebase. These practices improve code quality and make it easier to scale and maintain.