React: useAutoAnimate causes unnecessary renders
drmercer opened this issue Β· comments
Hi! π
Firstly, thanks for your work on this awesome project! π This is such a slick way to add animation with almost no effort!
I noticed that useAutoAnimate
returns a new setEnabled
function every time it's called. This causes unnecessary renders (and effect calls) if other hooks depend on that function.
I believe the solution is to use useCallback
so that setEnabled
is not re-created unless it has to be. I used patch-package to fix the issue locally - here is the diff that solved it for me:
diff --git a/node_modules/@formkit/auto-animate/react/index.mjs b/node_modules/@formkit/auto-animate/react/index.mjs
index 606d2da..387bf2a 100644
--- a/node_modules/@formkit/auto-animate/react/index.mjs
+++ b/node_modules/@formkit/auto-animate/react/index.mjs
@@ -1,4 +1,4 @@
-import { useRef, useState, useEffect } from 'react';
+import { useRef, useState, useEffect, useCallback } from 'react';
import autoAnimate from '../index.mjs';
/**
@@ -9,11 +9,11 @@ import autoAnimate from '../index.mjs';
function useAutoAnimate(options) {
const element = useRef(null);
const [controller, setController] = useState();
- const setEnabled = (enabled) => {
+ const setEnabled = useCallback((enabled) => {
if (controller) {
enabled ? controller.enable() : controller.disable();
}
- };
+ }, [controller]);
useEffect(() => {
if (element.current instanceof HTMLElement)
setController(autoAnimate(element.current, options || {}));
This issue body was partially generated by patch-package.
I'll accept this if you want to provide it as a PR. Thanks!
@justin-schroeder I made a PR for this couple of days ago, let me know how it goes π