Components
Definition
A component represents a part of the user interface. Usually, an application has 5 components:
Header
Side navigation
Main Content
Footer
Root (App) Component
Components are reusable, and can be used with different properties to display different information. A component is usually contained within a JavaScript file, such as App.js.
Types of Components
React has two component types:
State-less Functional component: JavaScript functions that return HTML component for the UI.
Stateful Class Component: They are ES6 classes, which extend the Component class. They must have a Render method returning HTML.
Functional Components
JavaScript functions that can optionally receive object as properties (props) and return HTML (JSX).
// Functional component
import React from 'react'
const Greet = () => {
return (
<h1> Hello Vishwas </h1>
)
}
export default Greet
You can import a functional component as follows:
import Greet from './Greet.jsx'
render (
<Greet/>
)
Class Components
Basically ES6 classes. They can also receive props and return HTML. Apart from that, they can also maintain a private internal state (some information private to that component).
Here's how we can create a class component:
// Class component
import React, { Component } from 'react';
class Welcome extends Component {
render() {
return <h1> Welcome! </h1>
}
}
export default Welcome
You can import a class component in the same way as a functional component.
When to use functional and class components?
Functional components:
Simple functions
Use as much as possible
Absence of 'this' keyword
Solution without using state
Stateless/dumb/presentational
Class components:
Feature-rich
Complicated UI logic
Maintain their own private data in the form of state
Provide lifecycle hooks
Stateful/smart/container
React Hooks in v16.7.0-alpha
React Hooks let you use state and other React features without writing a class component. So functional components are now like class components!
Last updated