What are components?
Components are basically building blocks which let you split UI into different pieces which are independent and reusable .
Components work similar to JavaScript functions.
They accept random or arbitrary inputs called props and return React elements which describe what should appear on the screen that is UI.
Following are two types of components in React.
1.Class Component
2.Functional Component
1.Class Components:-
Class component is a stateful component i.e. it controls the changes in the state and the implementation of the component logic , Basically it is a regular ES6 class that extends the component class of the React library.
These components have access to all the different phases of a React lifecycle methods
class MyClass extends Component {
constructor() {
super();
}
render() {
return (
<>
<h1>This is a Class Component</h1>
</>
);
}
}
export default MyClass ;
Lifecycle of Components:
There are major three phases in the life cycle
1.Mounting
2.Updating
3.Unmounting
Mounting : It means putting elements into DOM
Following are four built in methods that are called in a order when mounting a component
• constructor()
• static getDerivedStateFromProps()
• render()
• componentDidMount()
Updating: This is the phase when some change occurs in state or props. When states or props causes any change ,following methods are called in the order
1. static getDerivedStateFromProps()
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate()
5. componentDidUpdate()
Unmounting: This method gets called when a component is being removed from the DOM
• componentWillUnmount()
Pure Component:-
A React component is considered pure if it renders the same output for the same state and prop ,for this type of class component .
Which means they are deterministic in nature for specific input parameters we always have specific output, that is output is dependent only on Input parameters no other external variable has any effect on them.
React provides the PureComponent base class. Class Components which extends the React.PureComponent class are called as pure components
If we extend a class with Pure Component then there is no need for shouldComponentUpdate() Lifecycle Method.
What ReactJS Pure Component Class does is it compares current state and props with new props and states to decide whether the React component should re-render itself or not.
Let’s understand this with an example :
Normal React component :
class Greeting extends React.Component{
shouldComponentUpdate(){
return false;
}
render(){
return <h1>Hello Everyone </h1>
}
}
Pure Component:
class Greeting extends React.PureComponent{
render(){
return <h1>Hello Everyone</h1>
}
}
2.Functional Component:-
The most simplest way to define a component in React is to write a javascript function.
Functional Components are basic javascript functions.
Generally we use arrow functions to create a component but we can also create with the regular function keyword.
Functional Components are stateless components as they simply accept data and display it in some form which means they mainly responsible for rendering UI
we do not use the render method here because For a functional component, the component is a function that itself returns what you want to render.
We cannot use React lifecycle methods in Functional Components
functional components do accept and use props but for using states in functional components we need to use React hooks.
Eg: Functional Component
const MyFunction =()=>{
return(
<h1>This is Functional Component</h1>
)
} export default MyFunction;
React Forms and Components:
Forms are an integral part of any web application ,It allows users to interact with the application as well as with the use of forms we can gather information from the user.
Forms can perform a variety of tasks and may contain different types of fields.
In HTML form data is usually handled by the DOM whereas in React it is handled by the components.
Following are mainly two types of form input in React
1.Uncontrolled Component
2.Controlled Component
1.Uncontrolled Component :
These Components are similar to HTML form inputs.here data is controlled by the DOM itself .
They store its own state internally,and you can query the DOM using a ref to find its current value when you need it .
To write an uncontrolled component ,there is no need to write an event handler for every state update also it has limited control over the form elements and data and it does not allow validation control
Example:
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.handleChange = this.handleChange.bind(this);
this.input = React.createRef();
}
handleChange = (newText) => {
console.log(newText);
}
render() {
return (
<div className="App2">
<div className="container">
<input type="text"
placeholder="Your message here.."
ref={this.input}
onChange={(event) => this.handleChange(event.target.value)}
/>
</div>
</div>
);
}
}
export default App;
2.Controlled Component:
Controlled Components takes current value through props and notifies changes through event based callbacks.
It does not maintain its internal state ,here data is controlled by the parent component.
It allows validation control and it also has better control over the form element and data
Example:
import React, { useState } from "react";
export default function App() {
const [inputValue, setInputValue] = useState("");
const handleInputChange = (e) => {
setInputValue(e.target.value)
}
const handleSubmitButton = () => {
alert(inputValue);
};
return (
<div className="App">
<input value={inputValue} onChange={handleInputChange} />
<input type="submit" value="submit" onClick={handleSubmitButton} />
</div>
);
}
What is Hook?
As class components are confusing,Hooks were introduced in React version 16.8
Hooks do allow functional components to have access to state and other React features.
The simplest hook or most commonly used hook is the useState hook, It takes initial state as an argument. useState is a function that returns an array with two items in it: the first is the actual state and the second is a function that sets the state.
Basic Hooks:
• useState()
• useEffect()
• useContext()
Rules of Hooks:
Hooks are basically Javascript functions but they impose additional rules:
• Hooks can only be called inside React function component that is You cannot use outside it in class component or anywhere out of functional component
• Hooks can only be called at top level of a component
• Hooks cannot be conditional
Examples of Hooks :
1. useMemo:-
const memoizedResult = useMemo(compute, dependencies);
React has a built-in hook called useMemo that allows you to memoize expensive functions so that you can avoid calling them on every render.It accepts 2 arguments a function compute which computes a result and the dependencies array
During initial rendering, useMemo(compute, dependencies) invokes compute, memoizes the calculation result, and returns it to the component. If during next renderings the dependencies don’t change, then useMemo() does not invoke compute but returns the memoized value
2. useRef:
const reference = useRef(initialValue);
After the evolution of functional components, functional components got the ability to have a local state that causes re-rendering of the component once there is an update to any of their local state. Eg whenever there is an update in useState it will cause re-rendering of corresponding component here useRef comes in the picture
The useRef Hook allows you to persist values between renders.It can be used to store a mutable value that does not cause a re-render even when it is updated.It can be used to access a DOM element directly.It accepts one argument as an initial value and returns a reference (aka ref). A reference is an object having a special property called current.
reference.current accesses the reference value, and by using reference.current we can update the reference value .
Props:
Props is a short form of Properties.
We use props in React to pass data from one Component to another that is from Parent component to child component
Props are passed to components via HTML attributes .
When we want the flow of data in an app to be dynamic, props are very useful.
You can send single as well as multiple props in React
Render props:
In react it is possible to use a prop whose value is a function to control what is actually rendered by a component .
Render prop is a technique for sharing code between react components using a prop whose value is a function.This enables us to share common functionality between the components that is fundamentally it solves problem of react component logic code reuse in a much easy and superior way
Example of Props;
Parent Component:
import Greet from "./Greet";
function App() {
return (
<div className="App">
<Greet name="Leonardo" />
</div>
);
}
export default App;
Here App is a Parent Component and Greet is a children component.
And we are passing data from App component to Greet component
Children Component:
const Greet =(props)=>{
return(
<>
Welcome {props.name} Let's learn React
</>
)
}
export default Greet;
Here in the Greet component Welcome and Let’s learn React is hardcoded string whereas we are getting name Leonardo dynamically from the parent component by using prop.