On the other hand, when defining a class component, you have to make a class that extends React.Component. The JSX to render will be returned inside the render method. First of all, the clear difference is the syntax. Just like in their names, a functional component is just a plain JavaScript function that returns JSX. A class component is a JavaScript class that extends React.Component which has a render method. A bit confusing? Let’s take a look into a simple example. Basically the same thing happens here: componentDidMount is a lifecycle method that is called once after the first render.
And so to answer our question before, you should use functional components
if you are writing a presentational component which doesn’ t have its own state or needs to access a lifecycle hook.Otherwise you can stick to class components or take a look into the library recompose which allows you to write functional components and enhance them with a state or lifecycle hooks with HOCs!
Source: https: //djoech.medium.com/functional-vs-class-components-in-react-231e3fbd7108
import React from "react";
const FunctionalComponent = () => {
return <h1>Hello, world</h1>;
};
import React from "react";
function FunctionalComponent() {
return <h1>Hello, world</h1>;
}
import React from "react";
class ClassComponent extends React.Component {
render() {
return <h1>Hello, world</h1>;
}
}
<Component name="Shiori" />
The class component, a stateful/container component, is a regular ES6 class that extends the component class of the React library. It is called a stateful component because it controls how the state changes and the implementation of the component logic. Aside from that, they have access to all the different phases of a React lifecycle method. The class component uses ES6 class syntax, and it extends React components with a render method that returns React elements. On the other hand, functional components with hooks are purely JavaScript functions that also return React elements. Complex components are hard to understand in the class component.
Before the advent of React Hooks, the class component was the only option to create a dynamic and reusable component because it gave us access to lifecycle methods and all React functionalities.
To demonstrate using the class component, let’s create a simple Counter component that allows users to increase or decrease a number. We will also exhibit a bit of the lifecycle methods in our example below.
// demonstrating a Class component
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
this.setState({ count: this.state.count + 1 });
}
handleIncrement = () => {
this.setState({ count: this.state.count + 1 });
};
handleDecrement = () => {
this.setState({ count: this.state.count - 1 });
};
render() {
return (
<div className="counter">
<h1 className="count">{this.state.count}</h1>
<button type="button" onClick={this.handleIncrement}>
Increment
</button>
<button type="button" onClick={this.handleDecrement}>
Decrement
</button>
</div>
);
}
}
export default Counter;
With hooks, composing components in React is more straightforward. React has two most commonly used hooks: the state (useState) and the effect (useEffect) hooks. We will demonstrate how to use both in the example below. However, if you are new to React, you can learn more about React Hooks here.
To demonstrate the difference between functional and class components, let us reimplement the previous class Counter component to a functional component.
// demonstrating a functional component
const App = () => {
const [count, setCount] = useState(0);
useEffect(() => setCount((currentCount) => currentCount + 1), []);
const handleIncrement = () => setCount((currentCount) => currentCount + 1);
const handleDecrement = () => setCount((currentCount) => currentCount - 1);
return (
<div className="counter">
<h1 className="count">{count}</h1>
<button type="button" onClick={handleIncrement}>
Increment
</button>
<button type="button" onClick={handleDecrement}>
Decrement
</button>
</div>
);
};
export default App;
Since you already understand what this Counter component does from our previous explanation, let’s look at how functional components implement this compared to the class component.
First of all, you don’t need a constructor or the render methods since it’s just a function and not a class. Hooks enable you to integrate all the necessary features of React Library previously available only to the class component, so with useState, you can add states to functional components. As we did above, we imported useState from React to set the initial state of count to 0. The useState hook will return a pair of values: the current state and a function that updates it. Take a look at the code section below as compared to how we implement states in class component with this.state and this.setState.
Const[count, setCount] = useState(0);
In this article, we’ve taken a close look at React components. By now, you should have a good understanding of the role components play in React apps, and the key differences between class and functional components. Since functional components are not objects, you must use React hooks to manage state and lifecycle events. Hooks were not introduced into React until version 16.8, but they have effectively made class components redundant. Functional components are also known as stateless components because they aren’t class objects and don’t maintain state. You can pass props to functional components as arguments, and they can return HTML.
return ( <p>Hello, World</p> )
return (
<WelcomeMessage />)
function WelcomeMessage() { return ( <p>Hello, World</p> )}export default WelcomeMessage;
let place = "Unknown";switch (SomeCondition) { case condition1: place = "Ukraine"; break; case condition2: place = "Russia"; break; case condition3: place = "US"; break; default: place = "World"; break;} return ( <p>Hello, {place}</p>)
import { Component } from 'react';class MyComponent extends React.Component { constructor(props) { super(props); this.state = { currState: true } } render() { <div> <p>Hello, World!</p> </div> }}
Class Component: This is the bread and butter of most modern web apps built in ReactJS. These components are simple classes (made up of multiple functions that add functionality to the application). Make a counter app that will increase the number of counts as users click on the “Add” button using Functional and Class components. Functional Components: Functional components are some of the more common components that will come across while working in React. These are simply JavaScript functions. We can create a functional component to React by writing a JavaScript function.
Syntax:
const Car=()=> {
return <h2>Hi, I am also a Car!</h2>;
}
Example:
import React, { useState } from "react";
const FunctionalComponent=()=>{
const [count, setCount] = useState(0);
const increase = () => {
setCount(count+1);
}
return (
<div style={{margin:'50px'}}>
<h1>Welcome to Pretagcode for Pretagcode </h1>
<h3>Counter App using Functional Component : </h3>
<h2>{count}</h2>
<button onClick={increase}>Add</button>
</div>
)
}
export default FunctionalComponent;
In class components, the render method will be called, whenever the state of the components changes. On the other hand, the Functional components render the UI based on the props. Class Components should be preferred whenever we have the requirement with the state of the component. Whenever we have the use case with the State of the component and rendering the UI based on the Component State, use the Class Components React facilitates the developer with Class Component and Functional Components
class Welcome extends React.Component {
render() {
return <h1>Super Excited to post my first post in Dev Community</h1>;
}
}
function welcome(props) {
return <h1>Super Excited to post my first post in Dev Community</h1>;
}
const welcome = (props) => <h1>Super Excited to post my first post in Dev Community</h1>;
To return our h1 we need the render() method inside a class component. Class components are classes that extend React.Component: Class components are more complex: they are instances of React.Component with the constructor in it and complicated system of methods for manipulating state and lifecycle. And we get an undefined error because we try to render a component that was declared with an arrow function before we initialize it.To repair the code just re-order the declaration and put it before calling render().
Functional components in React are just JavaScript functions like this:
function Foo(props) {
return <h1>Who is living young, wild, and free? - {props.name}</h1>;
}
const element = <Foo name="Me!" />;
ReactDOM.render(element, document.getElementById('home'));
Another way of writing function components is by using an arrow function.
An example of an arrow function:
const App = () => { //that is an arrow function
const greeting = 'Hello Function Component!';
return <Headline value={greeting} />;
};
const Headline = ({ value }) =>
<h1>{value}</h1>;
export default App;
Let’s start with an example:
class Foo extends React.Component {
render() {
return <h1>Who is living young, wild, and free? - {this.props.name}</h1>;
}
}
Functional components are JavaScript functions:
function FunctionalComponent() {
return <h1>Hello, world</h1>;
}
class ClassComponent extends React.Component {
render() {
return <h1>Hello, world</h1>;
}
}
This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript functions. You can also use an ES6 class to define a component: Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen. The simplest way to define a component is to write a JavaScript function:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
const element =
<div />;
function Welcome(props) { return <h1>Hello, {props.name}</h1>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
const element = <Welcome name="Sara" />;root.render(element);
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" /> <Welcome name="Cahal" /> <Welcome name="Edite" /> </div>
);
}