How Does React Works?
React lets us pass information to a Component using props (stands for properties). Props are global variables or objects. We will discover passing props to any component as we declare attributes for any HTML tag in detail in the article.
Components allow us to separate the UI into independent, reusable pieces and think about each piece in isolation. Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements that should appear on the screen. Developers can join the best React online course by clicking on the link provided.
What are Components?
React components break up the user interface into distinct pieces that can be reused and managed independently. The component takes an optional input and yields a react piece.
A React component can be "stateful" or "stateless."
"Stateful" components are class types, while "stateless" components are function types.
Source - Learnsimpli
Stateless Component
An Example of Stateless Component is as below:
import React from 'react';
const FirstComponent = (props) => {
return ( <h1>Welcome to the first Stateless Component Program!</h1>);
}
export default class App extends React.Component {
render() {
return (
<div>
<FirstComponent/>
</div>
);
}
}
The above example illustrates a stateless component
FirstComponent which is inserted in the <App/> component.
The FirstComponent is an <h1> element.
Stateful Component
import React from 'react';
class FirstComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
heading: "This is the First Stateful Component!"
}
}
render() {
return (
<div>
<h1 > {this.props.welcomeMsg} < /h1>
<h2 > { this.state.heading} < /h2>
</div>);
}
}
export default class App extends React.Component {
render() {
const welcomeMsg="Welcome to the React first Component Programming!";
return (
<div>
<FirstComponent welcomeMsg={welcomeMsg}/>
</div>
);
}
}
The above example illustrates a stateful component named FirstComponent, inserted in the <App/> component.
The FirstComponent consists of a <h1> and the <h2> wrapped in a <div>. The <h1> data is displayed using props and the <h2> is taken from the internal state of the FirstComponent.
Advantages of React Components
React.js is the most famous and popular front-end JavaScript library for creating Web applications. It is maintained by Meta (Facebook) and a community of professional and skilled developers. It is understood to be fast, scalable, simple, and highly advantageous to be utilized to develop large web applications; the data is updated without reloading the page.
There is a solid set of reasons it is widely used by startups and Fortune 500 companies alike; let us look at the advantages it offers.
Code Reusability
A ReactJS web application has multiple components, logic, and controls. These components are accountable for delivering a reusable piece of HTML code that can be reused to create other applications. The reusable code aids to make apps more manageable and easier to develop. These components enable us to build complex applications by nesting simple building blocks. Nesting block code helps in writing cleaner code. ReactJS utilizes a virtual DOM-based device or tool to load data in HTML DOM. The virtual DOM operates quickly as it only alters individual DOM elements rather than refilling the complete DOM every time.
We should aspire to reuse code whenever it is to be used across multiple components
Creating Reusable Form Component
Create a file named Reusablecomponent.js
import React from "react";
import PropTypes from "prop-types";
function ReusableComponent(props) {
return (
<React.Fragment>
<form onSubmit={props.formSubmissionHandler}>
<input
type='text'
name='Personnames'
placeholder='Person Names' />
<input
type='text'
name='firstlocation'
placeholder='FirstLocation' />
<textarea
name='firstissue'
placeholder='Describe the first component.' />
<button type='submit'>{props.buttonText}</button>
</form>
</React.Fragment>
);
}
ReusableForm.propTypes = {
formSubmissionHandler: PropTypes.func,
buttonText: PropTypes.string
};
export default ReusableForm;
Using Reusable Form Component
Now let's refactor our NewBuildForm to use this reusable component. Import the Reusablecomponent and then update return():
Create a new file NewBuildForm.js
import ReusableComponent from "./Reusablecomponent";
return (
<React.Fragment>
<ReusableComponent
formSubmissionHandler={handleNewTicketFormSubmission}
buttonText="Help!" />
</React.Fragment>
);
}
Fast Development
React allows developers to use separate parts of their application on both the client-side and the server-side, which eventually increases the speed of the development process.
Developers can code individual parts and reuse them in other modules, which enhances performance.
Performance Consistency
ReactJS enhances performance due to virtual DOM. It is a cross-platform and programming API that vends with HTML, XML, or XHTML. Most developers encounter the problem of DOM slowing down the application's performance. ReactJS cracks the problem by introducing virtual DOM. The React Virtual DOM exists in memory and represents the web browser's DOM. Because of this, we are writing virtual components that react and will turn into the DOM, leading to smoother and faster performance and consistency.
Scalability and Maintainability
Scalability and maintainability are the two main aspects. React is scalable as it is easy of adding new code, alter the old one, and fix bugs. React is suitable for large and complex applications. Many examples of big applications that use React, and the sites are working well — Facebook, Instagram, and Netflix. React is effortless to pull new components or combine a few components into one. React is modular and is easy to extract the common part of the application and can be reused in different parts of the product or migrated to other applications in the project if necessary. High cohesion, low coupling, and components reusability seem good for the programmers.
Easy Integration
React’s ideas are fairly straightforward to understand, so the development team can be changed and extend them without extra costs. React arrives with JSX, an optional syntax extension, making it possible to write your components. React comes with Components, hooks and many reusable components which makes it easy to integrate. All these component rendering creates a delightful experience for developers.
With the best course for web development on react training and immersive learning experience we can expect a rewarding career as a developer.
Two Ways the Components Receive Data
State
An updatable structure has data or information about the component and can be changed over time. The state transition can occur as a reply to user activity or system event. The React state is the heart of the react component that defines the component's behavior and how it will render. A state must be as simple as possible. It can instantly be accessed or altered inside the element or by the component.
Below is an example of data that can be passed by using props
class FirstComponent extends Component {
render() {
return (
<SecondComponent name="First Child" />
);
}
}
const SecondComponent = (props) => {
return <p>{props.name}</p>;
};
Props
Props are read-only elements. It is an object which holds the value of attributes of a tag and operates similarly to the HTML attributes. It authorizes the passing of data from one component to other components. It is identical to function arguments passed to the component the same way as the arguments passed in a function. Props are immutable, so we cannot alter the props from inside the component.
Below is the example for Props
class Testing extends React.Component {
constructor() {
this.state = {
id: 10,
name: "testing"
};
}
render() {
return (
<div>
<p>{this.state.id}</p>
<p>{this.state.name}</p>
</div>
);
}
}
Difference Between State and Props
Sl. No | Props | State |
1 | Read-only | Changes can be synchronous |
2 | Immutable | Mutable |
3 | Props pass data from one component to another | It holds information about components |
4 | Props can be accessed by child components | State can be accessed by child components |
5 | Stateless components have Props | Stateless components don’t have State |
6 | Props components are reusable | State components are not reusable |
7 | Props are external | State are internal |
React Component Lifecycle
React class components have their phases. The component cannot be mounted and unmounted without updates or error handling.
A component’s lifecycle are divided into four parts:
- Mounting — A component created and inserted into the DOM.
- Updating — The component is delivered in the browser and acquires new updates.
- Unmounting — The component is not required and gets unmounted.
- Error handling — In a lifecycle method, when there is an error during rendering, in the constructor of the child component.
Source:Netguru
Mounting
Below are the methods called in the following order
- constructor()
- static getDerivedStateFromProps()
- render()
- componentDidMount()
Updating
These methods are called in the following order
- static getDerivedStateFromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
Unmounting
This method are called in the following order
- componentWillUnmount()
Error Handling
Below methods are called when there is an error in a lifecycle method
- static getDerivedStateFromError()
- componentDidCatch()
Mounting
constructor()
The constructor method gets executed before mounting to the DOM and rendering.
for e.g.
constructor(props){
super(props);
this.state = {
message: 'hello world this is my first program',
}
}
static getDerivedStateFromProps()
Rather than calling setState, getDerivedStateFromProps returns an object containing the corrected state.
static getDerivedStateFromProps(props, state) {
return {
message: 'updated msg from here',
}
}
static getDerivedStateFromProps(props, state) {
return null
}
render()
The render method is called after the static getDerivedStateFromProps method next in the lifecycle.
render(){
return (
<View>
<Text>{this.state.message}</Text>
</View>
)
}
componentDidMount()
After render() the Component is mounted to the DOM, and the method called in— componentDidMount(). When this method is called, we have rendered the UI element. DOM.
componentDidMount(){
this.setState({
message: 'i got changed in this year',
});
}
import React, {Component} from 'react';
import { View, Text } from 'react-native';
class App extends Component {
constructor(props){
super(props);
this.state = {
message: 'hello world this is my first porgram',
}
}
Updating
When the state or props are changed, the Component may need to be re-rendered. The Components are updated in simple terms.
static getDerivedStateFromProps()
The static getDerivedStateFromProps method is the first method to be invoked.
shouldComponentUpdate()
A component needs to be re-rendered when the state or props change within this lifecycle method
Example usage of shouldComponentUpdate:
Component changes when this.props.color or the this.state.count variable changes,
class CounterButtonTest extends React.Component {
constructor(props) {
super(props);
this.state = {count: 1};
}
shouldComponentUpdate(nextProps, nextState) {
if (this.props.color !== nextProps.color) {
return true;
}
if (this.state.count !== nextState.count) {
return true;
}
return false;
}
render() {
return (
<View>
<Button
color={this.props.color}
onPress={() => this.setState(state => ({count: state.count + 1}))}
/>
<Text>Count: {this.state.count}</Text>
</View>
);
}
}
After the shouldComponentUpdate method, a render is called instantly after that, relying on the returned value from shouldComponentUpdate, which by default is true.
getSnapshotBeforeUpdate(prevProps, prevState)
After the most recently rendered output is committed, the getSnapshotBeforeUpdate() method gets invoked.
<ScrollView
onContentSizeChange={()=>{this.scrollViewRef.scrollToEnd();}}
ref={(ref) => this.scrollViewRef = ref}
>
<Chats chatList={this.state.chatList} />
</ScrollView>
ScrollView is scrolled to the bottom, so you are updated with new messages.
componentDidUpdate()
componentDidUpdate() is invoked immediately after updation occurs.
componentDidUpdate(preProps) {
if(prevProps.selectedState !== this.props.selectedState){
fetch('https://pathToApi.com')
.then(resp => resp.json())
.then(respJson => {
this.setState({
isLoading: false,
data: respJson,
});
})
.catch(err => {
console.log(err)
})
}
}
Unmounting
componentWillUnmount()
componentWillUnmount() method invokes immediately before a component is unmounted and demolished.
// e.g add event listener
componentDidMount() {
el.addEventListener()
}
componentWillUnmount() {
el.removeEventListener()
}
Error handling
In real life, errors appear everywhere, and sometimes we are unaware of them. This part introduces basic ways of handling errors.
Let’s execute a simple component to detect errors in the demo app.
We will create a new component called ErrorBoundaryTest.
Here’s the most basic implementation:
import React, { Component } from 'react';
class ErrorBoundaryTest extends Component {
state = {
hasError: false,
};
render() {
return this.props.children;
}
}
export default ErrorBoundaryTest;
static getDerivedStateFromError()
Error is in a descendant component getDerivedStateFromError() method is called first, and the error is passed as an argument.
ErrorBoundaryTest Component to use this lifecycle method.
import React, { Component } from "react";
class ErrorBoundaryTest extends Component {
state = {
hasError: false,
};
static getDerivedStateFromError(error) {
console.log(`Error log from getDerivedStateFromError: ${error}`);
return { hasError: true };
}
render() {
if(this.state.hasError) {
return <Text> Something went wrong in the program :( </Text>
}
return this.props.children;
}
}
export default ErrorBoundaryTest ;
The error gets logged to the console, console.log(error), and the object is returned from the getDerivedStateFromError method.
Note
getDerivedStateFromError() is called during the “render” phase and hence side-effects are not permitted for those using componentDidCatch().
componentDidCatch(error, info)
The componentDidCatcherror method is called after an error component is thrown. It passes one more argument, which represents more information about the error.
componentDidCatcherror(error, info) {
logComponentStackToMyService(info.componentStack);
}
Let’s update the ErrorBoundary Component to use the componentDidCatch method:
class ErrorBoundaryTest extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
logComponentStackToMyService(info.componentStack);
}
render() {
if (this.state.hasError) {
return <Text>Something went wrong in the program.</Text>;
}
return this.props.children;
}
}
ErrorBoundaryTest catches errors from components; we’ll have the Component render whatever passed as default error UI
Create Your First Component
The component's term should begin with an upper case letter.
Class Component
A class component includes and extends React. Component statement. This statement creates an inheritance to React. Component and supplies component access to React.Component's functions.
The component also requires a render() method to return HTML.
class bus extends React.Component {
render() {
return <h2>Hi, I am travelling by bus!</h2>;
}
}
Function Component
The same example instead was created utilizing a Function component.
A Function component returns HTML and behaves the same as a Class component. Still, Function components are written utilizing less code and are easy to understand
function Bus() {
return <h2>Hi, I am traveling in Bus!</h2>;
}
Rendering Components
Component called Bus returns an <h2> element.
Use this component in the application and use the similar syntax as HTML: <Bus/>
ReactDOM.render(<Bus />, document.getElementById('root'));
Why it is Better to React
Before ReactJS, Frameworks like Angular and Ember concentrated more on model/view/controller-like practices known as MVC. These frameworks attempted to deliver more functionalities and solve most front-end development issues. React’s features like JSX (JavaScript Syntax Extension), Virtual DOM, One-way data binding Performance, Extensions, Conditional statements, Components and Simplicity wholeheartedly encourage its learning and deployment and establish it as more popular.
Learning “ReactJS” is crucial. It provides developers with much more accessibility to build highly engaging web applications and user interfaces in less time and create large-scale apps with frequently changing data. React's powerful, responsive,non-risky, user-friendly characteristics help developers and organizations to create robust and scalable products. It has changed the pathway of building web applications.
React's advanced features like React components, i.e., pieces of UI code that can be reused in different parts of an application. Style UI instances using styled components. React js hooks that are the latest additions help to use state, and other React features without writing a class and are backward-compatible. It also has a well-developed lightweight react testing library solution for testing React components.
Developers can attain expertise on React by joining the best React online course at Knowledgehut.