0

I am new to react, and I noticed 2 ways that components built, and wanted to know which to use when

this is the first type, seems like the logical one that I would always use

import React, { Component } from "react";
import { connect } from "react-redux";

class ConnectedForm extends Component {
    constructor() {
        super();
        this.state = {};
    }

    render() {
        return (
            <form>
              <div> blah blah</div>
            </form>
        );
    }
}
const Form = connect()(ConnectedForm);
export default Form;

but then there is this simple looking component with no class and it's not extending the component:

import React from "react";
import { connect } from "react-redux";

const mapStateToProps = state => {
    return state.locations;
};

const LocationsList = ({ locations }) => (
    <ul>
        {
             locations.map(el => (
            <li key={el.id}>
               Name - {el.name}, Address - {el.address}, Coordinates - {el.coordinates}, Category - {el.category}
            </li>
        )) }
    </ul>
);
const List = connect(mapStateToProps)(LocationsList);
export default List;

I was wondering whats the name of each approach, and when I should prefer the simpler one over the class one?

1 Answer 1

1

Usually you want to use a "Class based component" for anything thats going to have logic in it and a "Functional component" if it is only displaying data or doing simple interactions which you will pass in as props or use hooks.

Hope this helps.

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

2 Comments

Since hooks were released its preferred to use Functional components with hooks, which can do what class based components only could.
I mentioned that in my answer but still prefer to use a class based component when there is lots of logic, so not to have to set up hooks for every functionality I need. But in principal @Alvaro is right.

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.