Read it in 12 Mins
Prior to ReactJS, Popular frameworks like Angular and Ember were focused more towards model/view/controller like patterns known as MVC. These frameworks tried to provide more functionalities and solve most front-end development problems. ReactJS, however, chose to follow a different path, focusing primarily on views and how we can efficiently render views, thus popularising Component-based Architecture in web development.
I wouldn’t go so far as to say the creators of ReactJS invented the Component-based Architecture pattern, but for sure they saw its benefits and helped popularize this pattern for web development.
But first, what is Component-based Architecture?
In web development, final output is a fully functional UI. According to component-based architecture, we should see the complete UI as a combination of multiple smaller, reusable, composable, functional components and we should approach the problem in similar fashion. We should build multiple small, composable, functional components which can work together as a complete solution.
So, we understand that in component-based architecture, we are supposed to build plenty of smaller components. But what is a component and how does it look like?
The word "component" in software industry means a software package, a service or any module which encapsulate a set of related functionalities. In the context of UI development, a component means a UI element or a collection of UI elements which together provide some set of functionalities. A component could be as small and simple as a heading component which is builtwith single H1 tag and its text or it could be as complex as accordion or tabbed navigation. ReactJS also encourages web developers to build smaller, reusable, composable components.
There are lot of discussions about the benefits of using Component Architecture. Some people feel that if we break down the UI in multiple components interacting with each other,then the code base will have too many components and will eventually make the project un-maintainable. But still, this architecture has following benefits:
React component is basically a collection of one or many UI elements which renders a complete functionality. It can show different behaviours based on different parameters. In ReactJS, these parameters are knownas state of component and props passed to component. So how does a React component looks like?
A very simple components looks something like this:
import React from "react"; function Greeting({ name }) { return < h1 >{`Hello ${name}`}</h1>; } ReactDOM.render(<Greeting name="Gully Boy" />, document.getElementById("root"));
Alright. But<Greeting /> is not recognised by web browsers so won't it throw an error? Above code uses JSX (Syntax extension for JavaScript) and there are tools which actually converts JSX into something understandable by JavaScript engines of web browsers.
JSX is a library which allows us to write HTML (or XML) like syntax in JavaScript file. Then this code goes through a tool which converts it into something understandable by JavaScript engines. It allows us to write HTML in JS. It gives a syntax { <Any JS code >}, inside curly bracket, we can write JS code.
But still how does the final React component looks like? Below code snippet is a final conversion of above Greeting component.
import React from "react"; function Greeting({ name }) { return React.createElement("h1", null, `Hello ${name}`); } ReactDOM.render( React.createElement("Greeting", { name: "Gully Boy" }, null), document.getElementById("root") );
React.create Element is part of React API which actually defines a React element. This data structure will be used by React to render the DOM element later. So now, we understand the need of JSX and benefits of using JSX, We will be using React components using JSX in rest of the article.
Before going into the classification, we need to understand what a state means in React component. state is information that a component itself maintains and which changes with time. The state affects the UI and/or the behaviour of the component.
There are two types of components based on interactivity:
Stateless Component: When a React componentdoesn't have its own state and it just renders based on the information passed to component (props) or a hardcoded information within the component then such components are called as stateless component. Such type of component doesn't provide any user interactivity with component. For Ex: above Greeting component <Greeting name="John Smith" /> is a stateless component as it just renders the information (in this case name props) passed to it.
Stateful Component: There is other type of component which possesses state. This means based of the state behaviour of component changes. These types of components are known as stateful components. For Example a counter component below:
import React, {useState} from 'react'; function Counter() { const [value, setValue] = useState(0); const increment = () => { setValue(value + 1); } const decrement = () => { setValue(value - 1); } return ( <div> <button type="button" onClick={increment}>Decrement</button> <span>{value}</span> <button type="button" onClick={decrement}>Decrement</button> </div> ); } export default Counter;
Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component.
Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component.
Based on Programming Methodology
There are two type of components based on Programming Methodology
Class based Component: A React component can be JavaScript class which implements render method of ReactJS and extends React.Component class. Generally if a component has any state or need to implement any React lifecycle method then we create a class based component. Class based componentmust implement the render lifecycle method which returns the JSX. Stateless component can also be implemented as class based component. For example, Above <Greeting /> component can be implemented as class based component like below:
import React from 'react'; class Greeting extends React.Component { constructor(props) { super(props); } render() { return < h1 >{`Hello ${this.props.name}`}</h1>; } } export default Greeting;
Functional Component: A React component can be JavaScript function which returns JSX. Before Hooks which means before React v16.8, functional component was used only for building stateless component. Functional component takes props as argument and returns JSX. Writing functional code is always better in comparison to class based component because transpiled code for functional component is always shorter than class based component. For example, First implementation of <Greeting /> at the top is functional component.
There are two types of components categorised based on functionality. One typeimplementsbusiness logic and the other type is more inclined towards UI.
Presentational Component: React components which decide the look and feel of UI are called presentational component. These components can be stateful or stateless components. State of these components are normally UI level state instead of application (business logic) state. These components are reusable and often used to have independent styles. For example: above Greeting component is a presentational component which can we be reused multiple places in application.
Container Component: React component which mainly deals with application level state, rarely contains HTML tags and interact with API data are known as container component. This categorisation is basically separation of UI logic and application logic.
In React JS, class-based components are extended from React.Component class which provides several lifecycle methods to component. render is also a life cycle method which must be implemented in React component. Other lifecycle methods are optional and can be used to gain more control over the React component. As ReactJS has evolved with time, few lifecycle methods are no longer supported and will be removed from library in coming update. In this article, we will look into the lifecycle methods which are supported by library version 16.4+.
To understand component's lifecycle methods and their invocation orders, we can divide all the methods in three broad category: Mounting, Updating, Unmounting
Mounting: When component mounts then first of all constructor method (if present) is called. constructor method takes props as argument and pass props to the constructor method of React.Component class. Refer the example of class based component above. then getDerivedStateFromPropsstatic method will be invoked. getDerivedStateFromPropstakes two argument - props and state and returnsan object to update the state or returnsnull to update nothing. This lifecycle method is used when the state is dependson props. After getDerivedStateFromPropsmethod, render method is being called which returns the JSX. After render, componentDidMount is called which is the last method in mounting phase. We normally put API calls in componentDidMount lifecycle method. To summaries the mounting of component:
constructor
constructor(props) {
super(props);
// code here
}
getDerivedState From Props
static getDerivedStateFromProps(props, state) { // code here // return updated state object or null }
render
render() { // code here }
componentDidMount
componentDidMount() { // code here }
getDerivedState From Props
static getDerivedStateFromProps(props, state) { // code here // returns updated state object or null }
should Component Update
shouldComponentUpdate(prevProps, prevState) { // code here // returns true to re-render the component otherwise return false. // default is true }
render
render() { // code here }
getSnapshot Before Update
getSnapshotBeforeUpdate(prevProps, prevState) { // code here }
component Did Update
componentDidUpdate(prevProps, preState, snapshot) { // code here }
Unmounting: Last phase of React component is unmount. it invokes the last method of React component's lifecycle componentWillUnmount. this method is called before the component is unmounted and destroyed. Normally, clean up code is put in componentWillUnmount method. we should not call setState method here as component is never going to be re-rendered after unmount. To summarise:
componentWillUnmount componentWillUnmount() { // code here }
As JavaScript has evolved and tooling has become an essential part of web development. There are many approaches to start a React project but the most popular one is create-react-app (popularly known as CRA). create-react-app is available as NPM module which means to use CRA, one must have NodeJS and NPM installed on machine.
First check the NodeJS and NPM installation on machine by executing following command:
node --version npm --version npx –version
In case NodeJS is not install then download and install it from.
Once it is confirmed that NodeJS and NPM is installed on system then execute following command to create a React project:
npx create-react-app My First React Project
NPX command comes with NPM. It is used to use any NPM without actually installing the NPM. above command will create a new React project with latest version of create-react-app in your current directory. Execute following command to run the project:
cd My First React Project
npm start
This would start a local server at port number 3000 and open default React page in browser.
Above image shows the files and folder generated by CRA. let us go through it and understand:
CRA configured our React project with all the needed tooling required for web development. It configured Webpack, dev server with hot reload ( on file save browser reloads the page to reflect latest change), Eslint, react-testing-library for unit testing React components etc...
src/index.js is the starting point of our React project. Project also has one sample React component App.js. You can make changes to App.js and it will be reflected on browser.
So far, we have learnt different ways of writing React component. Now it is time to choose which pattern should you choose for writing React components. As we have discussed in previous article that ReactJS is moving towards functional programming paradigm and with the introduction of hooks in version 16.8, Writing functional component fulfils most of our use cases.
Let's create our first stateful functional component. We will be building a simple counter component. The final output looks like this:
Counter component code:
import React, { useState } from "react"; import "./Counter.css"; function Counter() { const [count, setCount] = useState(0); const increment = () => { const updatedCount = count + 1; setCount(updatedCount); }; const decrement = () => { const updatedCount = count - 1; setCount(updatedCount); }; return ( <div className="counterContainer"> <button type="button" onClick={decrement}> - </button> <span>{count}</span> <button type="button" onClick={increment}> + </button> </div> ); }
export default Counter;
Styles are added in Counter.css
.counterContainer { background-color: #fff; font-size: 24px; font-weight: 500; border: 1px solid #0874ce; border-radius: 3px; box-shadow: 1px 1px 4px 0 #0084ff; } .counterContainer button { outline: none; border: none; width: 50px; height: 40px; background-color: transparent; font-size: 24px; font-weight: 500; cursor: pointer; } .counterContainer span { color: #0084ff; }
We have created a fully functional counter component which can be used anywhere in React application.
Avail your free 1:1 mentorship session.