DEV Community

Discussion on: How to mimic componentDidUpdate() with React Hooks

 
savagepixie profile image
SavagePixie

If the effect concernX have to be trigged only on updates right after any user action or async stuff, IMO you better should rely on your component scope (props, states, sometimes ref or context, ...). Ex:

So, if I'm understanding right what you're saying and especially this example, what you propose is to use something that already exists and that we're already monitoring to decide whether an effect hook should execute or not (and play with how that something has been initialised), rather than creating a specific reference to know whether the component has been mounted or not. Is that so?

Thread Thread
 
devdufutur profile image
Rudy Nappée • Edited

Exactly, rely on data values ans data changes instead of component lifecycle. It seems to be the way hooks are designed.

Actually all your props should be observed and changes propagated in your component render flow, it's a really different approach than class components. Dan Abramov made a really detailed blog post about that here : overreacted.io/a-complete-guide-to...

Just an apetizer :

It’s only after I stopped looking at the useEffect Hook through the prism of the familiar class lifecycle methods that everything came together for me.

“Unlearn what you have learned.” — Yoda

Thread Thread
 
savagepixie profile image
SavagePixie

I like that approach

Thread Thread
 
shiraze profile image
shiraze

I'm still struggling with this approach. I have a really basic Class Component that calls an action creator (which is passed as a prop) if a particular prop is true and if another prop has changed, but only if that second prop isn't being changed for the first time.
The suggestion in the article by @savagepixie got me around my issue, but I can't see how I could use @devdufutur 's suggestion (which sounds sensible but unachievable in my use case!):

import React from "react";

export default class RequireLogon extends React.Component {
  componentDidUpdate(prevProps) {
    if (
      this.props.isLoggedIn &&
      this.props.logonExpiresAt &&
      prevProps.logonExpiresAt !== this.props.logonExpiresAt
    ) {
      this.props.loadPermissions();
    }
  }

  render() {
    return this.props.children || null;
  }
}

Any suggestions?

Thread Thread
 
devdufutur profile image
Rudy Nappée • Edited

I guess your RequireLogon component could have been a custom hook...

function useRequireLogon(isLoggedIn, expiration, loadPermissions) {
  const refExpiration = useRef(expiration);
  useEffect(() => {
    if (isLoggedIn && expiration !== refExpiration.current) {
      loadPermissions();
    }
    refExpiration.current = expiration;
  }, [expiration, isLoggedIn, refExpiration]);
}
Thread Thread
 
shiraze profile image
shiraze

I like that, primarily because what I had wasn't a "component" as such, but some sort of rule. This is certainly cleaner code. Thanks!