This content originally appeared on Bits and Pieces - Medium and was authored by Piumi Liyana Gunawardhana
React Hooks, Concurrent Mode, Higher-order Components, and More
React is well known for building interactive and rich UI components. Furthermore, these components depend on the data fetch from APIs.
As developers, we can use various data fetching techniques to feed data for these components. But have you ever evaluated the methods you choose in comparison with other options available out there?
This article will discuss different data fetching practices for React. In the end, you will be able to choose the best approach based on the application requirements.
1. The Fetch-API
The Fetch API is a simplified promise-based interface for fetching data. Also, Fetch API is easier to use in comparison to XMLHttpRequest.
Fetch API is a JavaScript API with underlying functions to handle Request and Response objects. You can also test it on your browser console, as all the browsers support it. The following code snippets show a simple example of using Fetch API in practice.
fetchEmployeesFetchAPI = () => {
this.setState({...this.state, isFetching: true});
fetch("https://domain.in/api/employees")
.then(response => response.json())
.then(result=> {
this.setState({employees: result, isFetching: false})
})
.catch(exception => {
console.log(exception);
this.setState({...this.state, isFetching: false});
});
};
fetchEmployees = this.fetchEmployeesFetchAPI;
However, Fetch API also have several drawbacks like not allowing cancelling requests and request timeouts, inability to intercept HTTP requests, etc.
Most of these issues are addressed in the stand-alone third-party package called Axios. Let’s see how we can use Axios in a React project.
2. Axios
Although Axios is a third-party library, it is the perfect replacement for Fetch API if you require more control and convenience over data fetching.
It is properly documented, simple, and offers an outstanding development experience.
Similar to Fetch API, Axios also returns a JS promise. But there is no need to resolve the promise twice like Fetch API since Axios always returns a JSON response.
The coding part is similar to the Fetch API, except for reducing steps and better error handling. Let’s see how we can implement the same example using Axios:
fetchEmployeesAxios = () => {
this.setState({...this.state, isFetching: true});
axios.get("https://domain.in/api/employees")
.then(response => {
this.setState({employees: response.data, isFetching: false})
})
.catch(exception => {
console.log(exception);
this.setState({...this.state, isFetching: false});
});
};
fetchEmployees = this.fetchEmployeesAxios;
But you might feel that both these methods seem too much complicated with all these promises handling with then() and catch() blocks. So is there a way to simplify it further?
We can reduce the complexity of the code by switching to Async/ Await.
Let’s restructure the above code snippet with async/await.
async fetchEmployeesAsync() {
try {
this.setState({...this.state, isFetching: true});
const response = await axios.get("https://domain.in/api/employees");
this.setState({employees: response.data, isFetching: false});
}
catch (exception) {
console.log(exception);
this.setState({...this.state, isFetching: false});
}
};
fetchEmployees = this.fetchEmployeesAsync;
Until now, I have discussed 2 basic data fetching techniques in React. Now it's time to move onto other areas related to data fetching.
Tip: Share your React components between projects using Bit (Github).
Bit makes it simple to share, document, and reuse independent components between projects. Use it to maximize code reuse, keep a consistent design, speed-up delivery, and build apps that scale.
Bit supports Node, TypeScript, React, Vue, Angular, and more.
3. Data Fetching in Higher-order Components
Higher-order components are complex components that are obliged to fetch the data and distribute them to child components.
These components can be nested implicitly, and some child components may use different representations of the fetched data. Besides, some components in the hierarchical structure may need no data at all.
Furthermore, it is a best practice that emerged with design systems separating the components that fetch data from those that display them.
The following example shows how we can implement data fetching with higher-order components:
import React, {Component} from 'react'
import EmployeeComponent from "./EmployeeComponent";
class EmployeeHOC extends Component {
constructor(props) {
super(props);
this.state = {
isFetching: false,
employees: []
};
}
render = () => < EmployeeComponent data = {
this.state.employees
}
isFetching = {
this.state.isFetching
}
/>;
componentDidMount() {
this.fetchEmployees();
}
fetchEmployees= [...]
}
export default EmployeeHOC
First, data fetching and state logic should be wrapped up into a higher-order component. Then the componentDidMount() method will invoke the fetchEmployees() method and the render() method will pass the state solely to the child component, which is EmployeeComponentin this case.
The child component will not care about anything like lifecycle methods, fetching data, or handling errors, and it will only focus on retrieving data in props and rendering them.
import React from 'react'
const EmployeeComponent = (props) => {
return (
<div>
{
this.props.data.map( employee =>
<div>{employee}</div>)
}
</div>
)};
export default EmployeeComponent
Apart from data fetching, higher-order components are also responsible for rendering its child components directly and responding to events originating from those child components.
Therefore it’s essential to understand that higher-order components can cause unexpected issues in some cases that can be resolved using Render-props.
4. Data Fetching in Render-props
Render prop components in React are the alternate type of higher-order components.
Similar to higher-order components, the render prop components can also be used for declarative data fetching.
The core concept in render props is to pass a prop to a component as a function. The prop will then be executed by the recipient object, which is often used in the render() method, thus named as render prop.
import {Component} from 'react'
import axios from 'axios'
class EmployeeRenderProps extends Component {
constructor(props) {
super(props);
this.state = {
isFetching: false,
employees: []
};
}
render = () => this.props.children(this.state);
componentDidMount() {
this.fetchEmployees();
}
fetchEmployees= [...]
}
export default EmployeeRenderProps;
EmployeeRenderProps code is quite identical to that of EmployeeHOC. The main disparity is in the render() method, which calls its props.children(), Since this component does not require to know much of its children, this expands the degree of abstraction.
Render props code is quite identical to that of higher-order components data fetching code, which we discussed earlier. The main difference is in the render() method, where we call its props.children() instead of wrapping in a higher-order component.
Using render props for data fetching is well recommended in scenarios where you have a deep component hierarchy.
5. Data Fetching with React Hooks
Although render props addresses issues in higher-order components, both these methods require you to restructure your component hierarchy. But, with React Hooks, you don’t need to do many changes to your component structure.
React Hooks was introduced with React 16.8 update, and it put a stop to the use of class components for data fetching, which was a wordy and complicated approach.
As we all know, useState() Hook is Invoked with the initial state. And it is used in functional components to preserve local states. Similarly, effect Hook is used for data fetching proposes, and it accepts a single function and runs it after each render by default.
The following example shows how we can use useEffect() Hook with Axios to fetch data.
import React, {useEffect, useState} from 'react';
import axios from "axios";
import EmployeeComponent from "./EmployeeComponent";
function EmployeeReactHooks() {
const [data, setData] = useState({
employees: [],
isFetching: false
});
useEffect(() => {
const fetchEmployees = async () => {
try {
setData({employees: data.employees, isFetching: true});
const response = await axios.get("https://domain.in/api/employees");
setData({employees: response.data, isFetching: false});
}catch (exception) {
console.log(exception);
setData({employees: data.employees, isFetching: false});
}
};
fetchEmployees();
}, []);
return (....)
}
export default EmployeeReactHooks
6. Concurrent Mode and Suspense
If you’re following the latest news regarding React, you’ve most possibly aware of Concurrent Mode by now.
The concurrent mode is a collection of new features that can be used in React applications to keep them responsive and active to user’s device capabilities.
In Concurrent Mode, Suspense is a technique that allows the components to view anything as a fallback while waiting to complete some lengthy process.
Suspense is not a data fetching library. It’s a method for data fetching libraries to interact with React whether the data a component is reading is still not available.
<Suspense fallback={<p>loading...</p>}>
<EmployeeComponent/>
</Suspense>
In the above example, EmployeeComponent is enclosed within the Suspense component that has a fallback prop. React renders <p>loading…</p> to the DOM if EmployeeComponent is awaiting an asynchronous task, like extracting employee details from an API.
But please note that the Concurrent Mode feature is still at the experimental stage.
Final Thoughts
We discussed several techniques and methods of data fetching in React in this article, and I think now you have a good understanding of them.
So, what is the best data fetching method for your React application?
The answer to that question is totally up to you based on your project’s complexity and requirements.
But if you are starting a new React project, I suggest you to use React Hooks, Concurrent Mode, and Axios which keeps things simple.
Thank you for Reading !!!
Learn More
- Build Scalable React Apps by Sharing UIs and Hooks
- Upgrading to React 17 and Webpack 5
- New JSX Enhancements in React 17
Things You Should Know When Fetching Data for React Components was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Piumi Liyana Gunawardhana
Piumi Liyana Gunawardhana | Sciencx (2021-02-09T23:50:03+00:00) Things You Should Know When Fetching Data for React Components. Retrieved from https://www.scien.cx/2021/02/09/things-you-should-know-when-fetching-data-for-react-components/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.