Home > other >  Differences in creating/using components in React
Differences in creating/using components in React

Time:11-06

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?

CodePudding user response:

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.

CodePudding user response:

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

  • Related