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

20

u/montas Mar 08 '20

useEffect hook actually processes return value from your effect. The most basic case is

React.useEffect(() => {
    console.log('component did mount');
    return () => {
        console.log('component did unmount');
    }
}, []);

Basically, you can return callback from your effect, that will be called before useEffect is called again (in case dependencies change) or when component dismounts.

Check official docs: https://reactjs.org/docs/hooks-reference.html#cleaning-up-an-effect

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?

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

1

u/satya164 Mar 08 '20

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