Table of Contents
React Function Component- Introduction
Welcome back friends, In React Function Components blog, we will go through React function component concepts like what is Function component is, how to create a function component, the difference between function and class functions, and when to use function components, and many more.
Prerequisites
-
For React Function Components Development – use as per your
requirement.
-
Local Installation: (Recommended)
- Node
- Npm
- Any Text Editor(Visual Studio – recommended)
- Online Editor: (For Quickstart – codepen, stackbliz)
-
Local Installation: (Recommended)
- Revise of React Concepts
- Knowledge of ES6
- Basic understanding of React
Let’s React,
What is a component:
“A Component is known as the core building blocks of React.“
Components in React return a part of JSX code that determines what should be rendered on the screen.
What is React function component:
“A Functional component in react is just a function which takes props as input/parameter and returns JSX as output.”
Function Components in react is the most simplistic way to describe a component by writing a JavaScript function.
Features of React Function Component
- Functional components don’t keep state or lifecycle methods.
- Functional components are also easy to read, debug, and test.
- Functional components provide better performance advantages, decreased coupling, and reusability.
React Function Component Example:
We can create a react functional component by writing a simple JavaScript function. These functions may or may not get inputs as parameters. In the functional Components, the return value is known as the JSX code that renders to the DOM tree.
function Welcome(props) {
return return <h1>Hello, {props.name} </h1>;
}
This function is called a valid React component if it accepts a single “props” (stands for properties) object argument with data and returns a React element. We call them “function components” because they are javascript functions.
Types of Components in React:
There are two standards types of components in React.
- Class Components and
- Functional Components.
Why Should You Use React Functional Component
- Easy to Understand
Eliminating lifecycle methods or modifying states that functional components can’t do can decrease your testing and debugging time.
- Better Performance
Functional and Class Components are the same internally, Functional Components will eventually have performance optimization.
- Easy to Debug
Functional components render things based on the props that are passed, which makes them accurate to debug.
- Easy to Reuse
Functional Components are generally easy to repurpose. In React, we render things in the component based on whatever we’re passing in, it should be easier to reuse components. Whether a check box, button, a container, or something else.
When You Shouldn’t Use a Functional Component
You should not use Functional Components when you either need to manage the state or use a lifecycle method.
The Difference between React Function vs Class:
Example: Normal Function Component.
function Message(props){
return <div>Hello {props.name}</div>
}
The important point that makes this type of component different from a class component is the missing state and lifecycle methods. This is why functional components are also known as stateless components.
Example: Functional component with Arrow function:
Functional component with Arrow function is as below:
const Message = ({name}) => <div>Hello {name}</div>
Example: Same Component as a Class component:
The same component though written as a class component:
class Message extends Component{
render(){
return <div>Hello {this.props.name}</div>
}
}
Note: If you have a class component with only a render method, it is good practice to make it a functional component.
React function components Props
React function components Props: To accept properties, a functional component accepts an argument as below example.
Example: Functional props
function ParentComponent() {
return (
<div>
<h1>Parent Component in React</h1>
<SubComponent title="Aspire Softserv" />
</div>
)
}
function SubComponent(props) {
return <p>{props.title}</p>;
}
React Function as Arrow function:
const SubComponent = props => ( <p>{props.title}</p>)
React Function Component – Lifecycle
In react Class Components, you may be used to lifecycle methods such as componentDidMount, componentWillUnmount, and shouldComponentUpdate. These are not available in Function Components, so let’s learn how to implement them.
Below are the traditional life cycle methods are used before hook
- Mounting: This is putting inserting elements into the DOM.
- Updating: This involves methods for updating components in the DOM.
- Unmounting: This is removing a component from the DOM.
First of all, you need to have no constructor in a Function Component. Usually, the constructor would have been used in a React Class Component to assign the initial state. You don’t need these methods in a Function Component, because you allocate the initial state with the useState hook and set up functions within the Function Component for business logic:
Example:
import React, {useEffect, useState } from 'react'; const App = () => { const initialCount =+ localStorage.getItem('savedCount') || 0; const [count, setCount] = useState(initialCount);
const doIncrement = () => setCount(currentCount => currentCount + 1);
const doDecrement = () => setCount(currentCount => currentCount - 1);
useEffect(() => localStorage.setItem('savedCount', count), [ count, ]);
return ( <div> <h1>{count}</h1>
<button type="button" onClick={doIncrement}> Increment </button> <button type="button" onClick={doDecrement}> Decrement </button> </div>
); }; export default App;
React Pure functional component
“A function is said to be pure if the return value is determined by its input values only and the return value is always the same for the same input values.”
A React component is said to be pure if it renders the same output for the same state and props. For React pure class components, React provides the PureComponent base class. Class components that extend the React.PureComponent classes are treated as pure components.
Why Pure Components?
Pure components have some performance improvements and render optimizations because React implements the shouldComponentUpdate() method for them with a shallow comparison for props and state.
Example:
import React, { useState, memo } from 'react';
const App = () => { const [greeting, setGreeting] = useState('Let’s React!'); const [count, setCount] = useState(0);
const doIncrement = () => setCount(currentCount => currentCount + 1); const doDecrement = () => setCount(currentCount => currentCount - 1); const doChange = event => setGreeting(event.target.value);
return ( <div> <input type="text" onChange={doChange} />
<Count count={count} /> <button type="button" onClick={doIncrement}> Increment </button> <button type="button" onClick={doDecrement}> Decrement </button> </div>
); };
const Count = memo(({ count }) => { return <h1>{count}</h1>; }); export default App;
Let’s conclude,
Conclusion:
We covered all the basics of what is component to how, when to implement react lifecycle, React pure function, and many other topics. Below is a short insight on React Function component.
React Function components are just plain JavaScript functions without state or lifecycle methods. We cannot call setState inside of them but can use hooks, like useState and useEffect instead.
if your Class Components needs to be a Functional Component, remember that if your Class Component only contains a render method, it should be changed to a Functional Component instead.
Last but not least, This is not a complete react component article; we have written more topics in the next section.
Ready to explore further or have questions? Contact us for more information.