DEV Community

loading...

Let's Talk Functional Components & Hooks

matthewpalmer9 profile image Matthew Palmer ・3 min read

Introduction

As someone who has primarily used React Components and React Pure Components, I'll admit -- I got WAY too comfortable. So comfortable, in fact, that I was missing out completely. It wasn't until I started working on my current project that I needed an efficient way to redirect users based on an action. Naturally, I stumbled upon two hooks: useEffect and useHistory. Let's talk about them.

The useHistory Hook

This hook was the answer to my redirect problems. It is perfect and easy to use. Here's the problem... you can't use this hook inside of a React Class Component or React Pure Component. It will throw an error that tells you to use a Functional Component. This is the point in which I stepped into a new world.

How do we even USE useHistory?

Here's a little snippet that shows how to properly use the useHistory hook:

import React, { useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import { api } from '../services/api.js';

export default function Dashboard(props) {
    const { authUser } = props;
    let history = useHistory();

    useEffect(() => {
        api.user.getUserList({user: authUser})
        .then(resp => console.log(resp))
    });

    return (
        <>
            {authUser.id ? (
                <>
                    <div>Hello {authUser.username}</div>
                </>
            ) : (
                history.push("/")
            )}
        </>
    )
}
Enter fullscreen mode Exit fullscreen mode

Basically, if information is passed into this Dashboard and there is no authenticated user in props, this functional component will redirect the user back to the home screen or landing page.

What is a Functional Component?

Let's explore what this is for a moment. First, let's take a look at a React Class Component:

import React, { Component } from 'react';

export default class Animal extends Component {
    render() {
        return (
            <div>

            </div>
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

Compare that with a functional component:

import React from 'react';

export default function Animal() {
    return (
        <div>

        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

As we can all see, there is a major difference between the two. For starters, it's much easier to pass in props in this way if we wanted to. But the big kicker is that we can take full advantage of React Hooks. Let's say that you need to fetch data upon the rendering of a component. Your React Class Component would look like this:

import React, { Component } from 'react';

export default class Animal extends Component {

    componentDidMount() {
       fetch("https://some-url.com/api")
       .then(resp => resp.json())
       .then(data => performSomeActionWith(data))
       .catch(err => console.log(err))
    }

    render() {
        return (
            <div>

            </div>
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

This will do the almost the same thing as useEffect:

import React, { useEffect } from 'react';

useEffect(() => {
    fetch("https://some-url.com/api")
    .then(resp => resp.json())
    .then(data => performSomeActionWith(data))
    .catch(err => console.log(err))
});

export default function Animal() {
    return (
        <div>

        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

The difference between componentDidMount and useEffect is important to understand, however. They are not the same. According to this source:

componentDidMount and useEffect run after the mount. However useEffect runs after the paint has been committed to the screen as opposed to before. This means you would get a flicker if you needed to read from the DOM, then synchronously set state to make new UI.

Conclusion

The purpose of this blog was to introduce React hooks and how to properly use them with functional components. However, it is important to not only understand how to use them but also WHY we use them -- What purpose do they serve and what problems do they solve? There are so many more hooks, and I encourage you to run off and explore them all! Leave a comment if you'd like to see a blog covering nothing BUT hooks. ;)

Thanks for reading! Happy coding!

Discussion (0)

Forem Open with the Forem app