I have a parent component with two event functions handleMouseEnter and handleMouseLeave. The child component receives these two functions via props, so my goal is to make some delay in the execution of these functions. Some "GanttDiagramAction" have the same order_id, and if so, after mouseEnter I don't need to re-render the child components.
When i use this func like this:
const [currentOrderId, setCurOrderId] = useState()
const handleMouseEnter = orderId => {
setCurOrderId(orderId)
}
const handleMouseLeave = () => {setCurOrderId(null)}
//over map
<Box>
{data.map(item => (
<GanttDiagramAction
onMouseEnter={() => handleMouseEnter(order_id)}
onMouseLeave={()=> handleMouseLeave()}
/>
)}
</Box>
Everything fine and child components not rerendered if "order_id" the same. But i need delay, and when i tried to use debounce, child component rerendered twice, even if order_id the same.
I have a parent component with two event functions handleMouseEnter and handleMouseLeave. The child component receives these two functions via props, so my goal is to make some delay in the execution of these functions. Some "GanttDiagramAction" have the same order_id, and if so, after mouseEnter I don't need to re-render the child components.
When i use this func like this:
const [currentOrderId, setCurOrderId] = useState()
const handleMouseEnter = orderId => {
setCurOrderId(orderId)
}
const handleMouseLeave = () => {setCurOrderId(null)}
//over map
<Box>
{data.map(item => (
<GanttDiagramAction
onMouseEnter={() => handleMouseEnter(order_id)}
onMouseLeave={()=> handleMouseLeave()}
/>
)}
</Box>
Everything fine and child components not rerendered if "order_id" the same. But i need delay, and when i tried to use debounce, child component rerendered twice, even if order_id the same.
Share Improve this question asked Mar 5 at 20:09 David AbramovDavid Abramov 537 bronze badges1 Answer
Reset to default 0So this solution is work for me:
// Debounced handleMouseEnter with a delay of 500ms
const debouncedHandleMouseEnter = useDebouncedCallback(orderId => {
setCurOrderId(orderId)
}, 500)
// Debounced handleMouseLeave with a delay of 500ms
const debouncedHandleMouseLeave = useDebouncedCallback(() => {
setCurOrderId(null)
}, 500)
// Memoize the functions to avoid recreating them on every render
const handleMouseEnter = useCallback(
orderId => {
debouncedHandleMouseEnter(orderId)
},
[debouncedHandleMouseEnter]
)
const handleMouseLeave = useCallback(() => {
debouncedHandleMouseLeave()
}, [debouncedHandleMouseLeave])