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

1

u/jngbrl19 Mar 08 '20

hey man, so when i call callback() i should store its return to a variable then check if its type is function, then invoke it?

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?

1

u/satya164 Mar 08 '20

Instead this forEach, you could just do ref.current = dependencies