forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Avoid calling setState in callback ref (vercel#18589)
- Loading branch information
Showing
4 changed files
with
100 additions
and
33 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
50 changes: 50 additions & 0 deletions
50
test/integration/link-ref/pages/click-away-race-condition.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import React, { useCallback, useEffect, useRef, useState } from 'react' | ||
import Link from 'next/link' | ||
|
||
const useClickAway = (ref, onClickAway) => { | ||
useEffect(() => { | ||
const handler = (event) => { | ||
const el = ref.current | ||
|
||
// when menu is open and clicked inside menu, A is expected to be false | ||
// when menu is open and clicked outside menu, A is expected to be true | ||
console.log('A', el && !el.contains(event.target)) | ||
|
||
el && !el.contains(event.target) && onClickAway(event) | ||
} | ||
|
||
document.addEventListener('click', handler) | ||
|
||
return () => { | ||
document.removeEventListener('click', handler) | ||
} | ||
}, [onClickAway, ref]) | ||
} | ||
|
||
export default function App() { | ||
const [open, setOpen] = useState(false) | ||
|
||
const menuRef = useRef(null) | ||
|
||
const onClickAway = useCallback(() => { | ||
console.log('click away, open', open) | ||
if (open) { | ||
setOpen(false) | ||
} | ||
}, [open]) | ||
|
||
useClickAway(menuRef, onClickAway) | ||
|
||
return ( | ||
<div> | ||
<div id="click-me" onClick={() => setOpen(true)}> | ||
Open Menu | ||
</div> | ||
{open && ( | ||
<div ref={menuRef} id="the-menu"> | ||
<Link href="/">some link</Link> | ||
</div> | ||
)} | ||
</div> | ||
) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters