React Components
React component is a Javascript function that returns a JSX element.
React component provides the below functionalities.
The main purpose of a React component is to define the displayed view and bind it to the code that drives its behavior.
To write React Components,we have two ways:
Functional Components:
These are the JavaScript functions that receives properties (props) and returns a JSX element. Properties(props) are used to Pass information to a Component.
Everything required for behavior is defined within the function body, and the class-related parts of object-oriented components are dropped.
Syntax:
Class Components:
Mainly Class components are built using an ES6 class. Creating a class component is pretty simple, just define a class that 𝐞𝐱𝐭𝐞𝐧𝐝𝐬 Component and Add a single empty method to it called 𝐫𝐞𝐧𝐝𝐞𝐫().
The 𝐞𝐱𝐭𝐞𝐧𝐝𝐬 keyword here is used to inherit methods and properties from the React.Component.
Different from functional components, class components must have an additional 𝐫𝐞𝐧𝐝𝐞𝐫() method for returning JSX element.
Syntax:
Props:
Using this.props in the render() body we can access the Properties (props) in a class components.
<MyComponent myProp = "This is passed as a prop." />
Using state :
The state is a JS object in which we store the component's data that changes over time.
When the state object changes, the component re-renders.
One of the benefits class components have over functional components is access to component state.
Initialising the state:
We can update the state by using setState(). We can provide function/object as an argument to set the state.
There are pros and cons in both cases but I would like to conclude that functional components are taking over modern React in the foreseeable future.
As we noticed in the above-attached images, a functional component is written shorter and simpler, which makes it easier to develop, understand. Class components are a little bit confusing, with so many uses of this.
Using functional components can easily avoid this kind of mess and keep everything clean.
Mainly, Class Components Renders the UI based on both props and state, Whereas Functional Components Renders the UI based only on Properties(Props).
So, we can Use Class Components whenever the state is required. Otherwise, use the Functional components.
Good going All the very best👍