useInsertionEffect other use-case
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 11.8k
- Forks
- 7.9k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 11
Description
Hello,
in the docs it is stated that useInsertionEffect should be used only by css-in-js library authors, I think I've came across an other use case. I'm using forwardRef with a type HTMLDivElement[] where through a callback ref I'm pushing the refs in to the array as so ref={(ref) => ref && innerRef.current.push(ref)} and syncing it outside with a useImperativeHandle
However this needs a cleanup whenever the component re-renders, since useInsertionEffect fires sync BEFORE the dom is mutated, it is perfect for the cleanup of the innerRef array.
The code is as follows
const ComponentReturningAnArray = React.forwardRef<HTMLDivElement[], { data: string[] }>(({array}, outerRef) => {
const innerRef = useRef<HTMLDivElement[]>([]);
useImperativeHandle<HTMLDivElement[], HTMLDivElement[]>(outerRef, () => innerRef.current, [innerRef.current]);
useInsertionEffect(() => {
innerRef.current = [];
});
return (
<>
{
data.map((d) => (<div ref={(ref) => ref && innerRef.current.push(ref)}>{d}</div>))
}
</>
)
});
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the documentation statement about useInsertionEffect and the provided ComponentReturningAnArray example. Check whether this ref-collection cleanup is an intended use case and determine how the documentation should describe it. Done means the guidance accurately reflects the supported use cases and the example is addressed.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, react
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100