0

I've been learning React following a couple different tutorials and I noticed some differences in the creation of components.

In one App.js file a component is made as follows:

import React, { Component } from "react";
import { BrowserRouter as Router, Route } from 'react-router-dom';

import ListEmployees from "./components/listEmployees";

class App extends Component {
  render() {
    return (
      <Router>
        <div className="App">
          <Route exact path="/" component={ListEmployees} />
          
        </div>
      </Router>
    )
  }
}

export default App;

And in another project the component is instead created like so:

import React, { Fragment, Component } from "react";
import { BrowserRouter as Router, Route } from 'react-router-dom';
import './App.css';

import ListEmployees from "./components/listEmployees";
import displayNavbar from "./components/navbar";

const App = () => {
  return (
    <Fragment>
      <div className="container">
        <ListEmployees />
      </div>

    </Fragment>
  )
}

export default App;

What is the difference between these two components and are there advantages to using one way over the other?

1
  • 2
    Searching for "react class based vs functional components" should find a lot of discussion. Commented Nov 5, 2021 at 19:12

2 Answers 2

1

Your first example is a class component. This used to be the only way to build React components (pre v16.8). In comparison to functional components, which is what your second example is, they can be more confusing. Developers, and Facebook, wanted easier ways to create React components.

Enter functional components, which utilize React Hooks (https://reactjs.org/docs/hooks-intro.html).

In my experience, functional components are easier to write, debug, and maintain. There are a few more complex problems that Hooks solve, which you can read about in the link I previously posted.

It's largely a matter of preference, but the vast majority of people I see use functional components.

Sign up to request clarification or add additional context in comments.

Comments

1

The first example you gave is a class component. The second is a functional component.

Class components are the original way to make components. According to Facebook, functional components are the future.

Official Docs: https://reactjs.org/docs/components-and-props.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.