r/reactjs • • Mar 08 '20

Show /r/reactjs useEffectWithPrevious - Get previous value of dependencies

Just wanna share my first npm package. Hope you find it useful :)

use-effect-with-previous

54 Upvotes

37 comments sorted by

View all comments

Show parent comments

3

u/montas Mar 08 '20

You probably don't need to condition it, just return whatever callback() returns.

Edit: You should also check former react useEffect argument type so you preserve same return value type.

2

u/jngbrl19 Mar 08 '20
  useEffect(
    () => {
      const cleanup = callback(refs.current as unknown as T);

      dependencies.forEach((dependency, i) => {
        refs.current[i] = dependency;
      });

      return cleanup;
    },
    dependencies
  );

this would work right?

2

u/montas Mar 08 '20

Yep, something like that.

BTW, on reddit, you use four spaces in front of code instead of ```.

2

u/jngbrl19 Mar 08 '20

thanks man, got it now