auto-animate
auto-animate copied to clipboard
init react autoanimate using callback ref instead of useEffect
The problem
The current implementation of react useAutoAnimate hook uses useEffect to trigger autoanimate(element), while this approach works when the element is already rendered, it doesn't work when element is not yet mounted.
here is a codesanbox that shows the problem ( you can notice animation does not work). here is an example where useAutoAnimate does not work:
function Component() {
const [visible, setVisible] = useState(false)
const [ref] = useAutoAnimate()
return (
<div>
{visible && <div ref={ref}></div>}
</div>
)
}
The solution
Using callback ref, it doesnt' matter if the element is rendered or not, since React calls ref callback when the element if rendered on the first time, this implies to use useCallback for the callback ref to guarantee it will run only on the first render of the element, because React uses referential stability to check if the callback ref should be run or not.
here is a codesanbox that solves the problem with callback ref.
The latest updates on your projects. Learn more about Vercel for Git ↗︎
Name | Status | Preview | Updated |
---|---|---|---|
auto-animate | ✅ Ready (Inspect) | Visit Preview | Jan 7, 2023 at 5:32PM (UTC) |
Also such code is used in example in docs. Could you fix it too?
Hey @ilmpc , No change is needed to the docs, This pull request introduce 0 breaking change
Hey @ilmpc , No change is needed to the docs, This pull request introduce 0 breaking change
Yeah, I understand. useEffect approach is used in the first example in "usage" section of docs. So I propose to replace it with ref callback too. I was thinking to do it myself, but found your PR
I'm not sure if we must change anything in the docs, the example that uses useEffect is correct, and that example does not use useAutoAnimate hook, so i feel like it's not needed to change that example
I can attest that this PR also helps fix this issue:
Left: Current (The animations between tabs are undesirable)
Right: After this PR + adding a key
prop to the parent
And if I add a key
prop to the parent (without this PR's code), then animations just stop working after switching tabs.
I'd love if this PR got merged!
@andreterron yeah that's a typical example for what this pr is attempting to fix!
@sventschui Done! this pr is ready to merge
@benrandja-akram I'm not a maintainer of this lib, just came across your MR as I was looking into the lib a bit myself
@sventschui sorry for the inconviniece
@benrandja-akram why did you close the issue? Are you no longer submitting it for merger?
@justin-schroeder it thas been here for long time, i thought maybe you are not interested or it is not in your roadmap.
Still interested! It just has to fit into a dev sprint. I'll get to it sooner or later 👍