What are some tips on refactoring lifecycle component methods into useEffect hook?

Viewed 30

I am trying to refactor the following into ES6 as a functional component. I considered looking into lodash decorators: https://www.npmjs.com/package/lodash-decorators#bind but are there tips on approaching refactoring class components like this to functional components compliant with ES6, especially when the logic in the lifecycle component methods get more complex?

constructor(props) {
        super(props);
        this._isMounted = false;
        this.state = {
            profilePictureFailedToLoad: false,
   
        };
        if (process.browser) {
            this.profileImage = new Image();
            this.profileImage.src = this.props.userInfo.userAssetUrl;
        }
        this.handleLoginClick = this.handleLoginClick.bind(this);
        this.handleLogoutClick = this.handleLogoutClick.bind(this);
        this.handleProfileClick = this.handleProfileClick.bind(this);
        this.handleModalClose = this.handleModalClose.bind(this);
        this.handleDeleteAccountClick = this.handleDeleteAccountClick.bind(this);
        this.handleDeleteAccountModalClose = this.handleDeleteAccountModalClose.bind(this);
    }

    componentDidMount() {
        this._isMounted = true;
    }

    componentDidUpdate(prevProps) {
        if (this.props.router.query.login === "true" && prevProps.router.query.login !== "true") {
        console.log("Updating...")
        }
    }

    componentWillUnmount() {
        this._isMounted = false;
    }

1 Answers

Eden.

I think that code is an abstraction of a production code. Right? A real code example would be easier but let's try to help:

Moving from class components to function components with hooks isn't too easy to picture in the beginning.

The _isMounted flag.

I do not know how that flag is used but you might not need it. If you do, you can use an useRef inside + useEffect;

I have to emphasize you probably do not need this implementation:

const ref = React.useRef(false);

React.useEffect(() => {
    // This will run only in the first render;
    ref.current = true;
    () => {
        ref.current = false;            
    }
}, [])

The componentDidUpdate

In case you need to render a loading instead of that console.log, you can move this logic to the return (render) part of the function component.

The handlers

You can probably attach them to each correspondent element. You can use React.useCallback to avoid child components to rerender if that makes sense to you.

The profileImage

How would that be used? I also believe this can co to the rendering part.

I do hope that can give you some good direction.

Related