The Redux Anti-pitch

Redux seems to be growing in popularity by the day. There are starter kits dedicated to making it easy to get started. While this may excite many, it has caused me to wearily check for the existence of dispatch functions each time I onboard to a new project.

Why not Redux?

While there are definitely apps where Redux could be useful, it is overused in simple applications. In this day and age, there are much less complicated ways of engineering your state.

SWR / React Query

The main use case I have seen for Redux has been API requests and error management for said. React Query and SWR are libraries designed to solve this exact problem. These libraries handle the asynchronous nature of API calls on your behalf, caching information based on the URL and automatically revalidating them according to your preferences. It's pretty much a drop-in replacement for the API fetching use case.

Personally, I prefer SWR. Let's take a look at a SWR data fetch implementation.

import useSWR from 'swr'

const fetcher = (...args) => fetch(...args).then(res => res.json())

export function useUsers() {
    return useSWR('/api/users', fetcher)
}

That's it. Let's say you want to retrieve details for a specific user instead

import useSWR from 'swr'

const fetcher = (...args) => fetch(...args).then(res => res.json())

export function useUsers(id: number) {
    return useSWR(id ? '/api/users/' + id : null, fetcher)
}

No null checks needed. It can even handle React Suspense to essentially automate your loading states with just a little bit of config. This is what my usual implementation would be:

import axiosInstance from './axios'
import useSWR from 'swr'

export function useEndpoint(url, config = {}) {
    return useSWR(url ? url : null, axiosInstance, {
        suspense: true,
        ...config
    })
}

export function useUsers() {
    return useEndpoint('/api/users/')
}

export function useUser(id: number) {
    return useEndpoint(id ? '/api/users/' + id : null)
}

For me, this is definitely the better, simpler way to go.