React: Should I use Functional Component or Class Component

Short answer, for any new projects use Functional Component. With the introduction of hooks in React 16.8, there is no reason to use class component. Facebook is also encouraging people to use functional component which might give better performance in future versions.

Functional Component example:

    import React, { useState } from 'react'

    function Counter() {
        const [count, setCount] = useState(0);

        function handleClick() {
            setCount(count+1);
        }

        return(
            <div onClick={handleClick}>
                <p>You clicked {count} times</p>
            </div>
        );
    }

Class Component example:

    import React from 'react'

    class Counter extends React.Component {
        constructor(props) {
            super(props);
            this.handleClick = this.handleClick.bind(this);
            this.state = {
                count: 0
            }
        }

        handleClick() {
            this.setState({ count: this.state.count+1 });
        }

        render() {
            return(
                <div onClick={this.handleClick}>
                    <p>You clicked {this.state.count} times<p>
                </div>
            );
        }
    }

Leave A Comment