A lighter alternative to Redux: React Query
Exploring React Query’s power to replace boilerplate with only a handful of code when handling async actions
What is React Query
Often referred to as React’s missing data-fetching library, React Query handles fetching, caching, synchronizing and updating server state in a relatively simple manner with just a few lines of code.
Developers can handle managing state in a variety of ways, including the use of React hooks like useState
or useEffect
, or employing state management libraries like Redux, the popular client state library, to store and provide asynchronous data throughout an application.
Server State vs. Client State
State management libraries work well with client state, however they lack efficiency and expose problems when dealing with async / server state. React Query’s docs explore the quality and characteristics of server state:
Is persisted remotely in a location you do not control or own
Requires asynchronous APIs for fetching and updating
Implies shared ownership and can be changed by other people without your knowledge
Can potentially become “out of date” in your applications if you’re not careful
TL;DR: Server state deals with any fetching or modifying data in the database, while client state does not.
How can it replace Redux?
Instead of using Redux to store data you get and modify from the server (i.e. fetch requests), React Query replaces the boilerplate code with just a few lines of React Query logic.
Queries
a query is a declarative dependency on an asynchronous source of data that is tied to a unique key.
- used for
GET
andPOST
methods, to retrieve data - React Query provides the
useQuery
hook that takes a unique key and a function that returns a promise - after storing data in cache with
useQuery
, you can access that data at any point withuseQuery
, which takes the unique key as an argument:const data = useQuery(‘unique key’)
Mutations
mutations are typically used to create/update/delete data or perform server side-effects
- used for
PATCH/PUT
andDELETE
methods, to modify data - React Query provides the
useMutation
hook
Often with Redux, we are fetching data from the server, and then updating our application state. React Query allows us to skip the step of updating state through it provided hooks, so we can re-fetch data easily.
With React Query, we can remove Action Creators, Middlewares, Reducers, and Loading/Error/Result states, using only a few lines of React Query logic, ultimately making an application more maintainable and easier to build new features.