DEV Community

Matthew Palmer
Matthew Palmer

Posted on

componentDidMount() VS useEffect()

Introduction

These two were the bane of my existence this week, and I think now is as good a time as any to talk about them.

React

Starting off in React, hooks are usually far from our first lesson. We deal with Components and Pure Components before we typically find a reason to use Functional Components. It wasn't until after I started learning Hooks that I realized they only work in Functional Components. This was huge because the first case I ran into where I needed a convenient way to redirect to another page, which was with the useHistory hook from react-router-dom. A whole new world opened up for me, but not all was well...

Conditional rendering

Here I am at a crossroads. This component needed to render based on a boolean. Is there a user signed in? Is their id equal to this object.user_id? If it's not, then I wanna history.push("/")!

But wait... useEffect, AND useLayoutEffect for that matter, will fire after the conditional rendering. Therefore, the object.user_id will never exist. Even with componentDidMount(), the conditionals run while the component mounts!

When both go wrong...

I took a different approach when I realized that neither tool would work for me. I required a conditional with my server response. Checking for an error before rendering to the page.
As it turns out, there are cases when certain code needs to be validated before API calls and hooks in general.

My workaround though? Put redirects in the API call rather than returning it with a component. Chances are, it's better to redirect before state has a chance to update your pages if a user was never authorized to view that content to begin with!

Here's a small snippet in case it helps anyone out there!

    useEffect(() => {
        let listID = props.match.url.split("/")[3];

        api.list.editUserListByUrl(listID)
        .then(resp => {
            if(!resp.err) {
                setUserID(+resp.listitem.user_id)
                setUrl(resp.listitem.url)
                setDescription(resp.listitem.description)
            } else {
                history.push("/dashboard");
            }
        })
    })
Enter fullscreen mode Exit fullscreen mode

Happy Tuesday, everyone!

Top comments (0)