React makes UI development seamless, hassle-free, and appealing. It flexes the opportunity as a component-based library for single-page web & App development. It is a freely accessible, open-source library that eliminates the need for additional building tools. Data rendering is managed with drag-drop and components.
Follow this blog to learn more about: React State Management Tools for Enterprise Application Service
There's no such restriction on the count of component creation. If a significant component is unmanageable, chunk it into child components for composing the application.
We pick and practice with different APIs, libraries, and hooks based on needs and preferences. It makes fetching, caching, and updating the data seamless and efficient.
React Query
is a collection of hooks or data-fetching library
offer powerful accessibilities. It enables on-time scalability, flexibility, and necessary modification at any stage.
Use of useQueryHook
useQueryHook pairs its accessibilities with any promise-based method. It requires a combination of unique keys and functions to return the output of the promise. Refetching, caching, and Query sharing will use with the unique key.
Use of useMutationHook
Like the useQuery Hook, the useMutation hook binds the promise key pairs and returns the outputs. More precisely, it enables you to add or update the server data by sending needful requests. Its implementation we have mentioned in this blog.
React Query is a wonderful asset for react developers that wipes off the burden of server state. It gives you better on your React Application. You can wipe off a bunch of code and enhance speed, interaction, performance, and end-user experience.
An explanation for data fetching and updating with react Query
Before practicing fetching and updating data, we need to load the project and react Query Axios. We are going to set the codebase deployment area. For this, follow the code:
npx create-react-app react-query
npm install react-query Axios
Now we need to get access to all the react-query hooks. For this, an App.js component and QueryClientProvider are available. Both will wrap with each other. It holds the entire data fetching. Use the below code and swap it with index.js.
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { QueryClient, QueryClientProvider } from "react-query";
const root = ReactDOM.createRoot(document.getElementById('root'));
const queryClient = new QueryClient();
root.render(
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
);
reportWebVitals();
Now remove returned JSX from App.js.
import './App.css';
function App() {
return (
<div className="App">
<h1>React Query</h1>
</div>
);
}
export default App;
We mentioned the useQuery Hook in the initial of this blog. Now we will see its implementation in the project. By the way, we have another hook, useEffect, that manages the data fetching along with page reload accessibility. But we wouldn't use it here.
React Query functionality; the method is simpler and more manageable than useEffect.
Const { isLoading, isFetching, error, data, status } = useQuery();
We will use public API using Axios and fetch the name list.
Next, create the FetchApi.js file. Initiate an async function for data fetching from the base URL(using Axios).
This file will export and import to App.js(main).
Now we will perform some react-query calls over here:
Begin by importing UseQuery
const { isLoading, isFetching, error, data, status } = useQuery();
useQuery() outputs two arguments: unique key and Async-function. When the async-function process is loading displays, we will get a response and manage the mapping users and list names inside JSX.
//FetchApi.js
import axios from "axios";
async function fetchPosts() {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/users')
return data
}
export default fetchPosts;
//App.js
import React from 'react'
import { useQuery } from 'react-query'
import fetchPosts from './FetchApi';
import './App.css';
function App() {
const { data, error, isError, isLoading } = useQuery('users', fetchPosts)
if (isLoading) {
return <div>Loading...</div>
}
if (isError) {
return <div>Error! {error.message}</div>
}
return (
<div className=''>
<h1 className='container'>Users Name</h1>
{
data.map((users, id) => {
return <li className='container' key={id}>{users.name}</li>
})
}
</div>
)
}
export default App;
//styles
.container {
display: flex;
align-items: center;
justify-content: center;
}
A fetch post is essential to include. Otherwise, we will receive an error and not get the desired output.
Here the data fetching completes. Now the second thing you want to understand is adding new data or modifying server data. Here are the steps:
We need to head on our application and submit some data to the backend. It is a very quick process.
We will create a form as a form.js component.
We will use the Hook to submit or data update requests and values. This Hook is useMutation() wraps three things: isLoading, error, and mutate.
Here, createName is an Async function that will initiate HTTP POST requests to the API.
Another hook will require here to manage the input elements state: useState().
import React, { useState } from 'react';
import { useMutation } from 'react-query';
import axios from 'axios';
import './App.css';
const Form = () => {
const [name, setName] = useState('')
const [message, setMessage] = useState('')
const { isLoading, isError, error, mutate } = useMutation(createName)
async function createName() {
const response = await axios.post('https://jsonplaceholder.typicode.com/users')
setMessage(response.data)
}
const onChange = (e) => {
setName(e.target.value)
}
const Create = () => {
mutate({ id: Date.now(), name })
}
return (
< >
<div className="">
<h1>Name</h1>
<label>List of Names:</label>
<input type="text"
value={name}
onChange={onChange} />
<button onClick={Create} >Create</button>
<p> Created a new Name ID: {message && message.id}</p>
<div className=''>
{isLoading
? "updating..." : ""
}
{
isError
? error.message : ""
}
</div>
</div>
</>
)
}
export default Form;
Head to the main component, App.js and import this component here:
import React from 'react'
import { useQuery } from 'react-query'
import fetchdata from './FetchApi';
import './App.css';
import Form from './form';
function App() {
const { data, error, isError, isLoading } = useQuery('users', fetchdata)
if (isLoading) {
return <div>Loading...</div>
}
if (isError) {
return <div>Error! {error.message}</div>
}
return (
<div className=''>
<h1 className=''>Users Name</h1>
{
data.map((users, id) => {
return <ul>
<li className='' key={id}>{users.name}</li>
</ul>
})
}
<Form /> <--------imported//
</div>
)
}
export default App;
After this, you can check out the output in the window. useMutation() has made the request post and get process simpler and updated the data according to our preference.
To reduce react application complexities, search for more hooks in react Query.
Read this blog to know more about eslint rules for react app development.