Home > database >  Is redux middleware for asynchronous work is better than custom hook which does http request
Is redux middleware for asynchronous work is better than custom hook which does http request

Time:12-26

I want to know which approach is better in which scenario:

  1. React custom hooks for http requests, where we put states for loading, error and data and then inside functional component we just use that hook get data and then render it to ui and/or save it to redux.

for example: `const useFetch = (query) => { const [status, setStatus] = useState('idle'); const [data, setData] = useState([]);

useEffect(() => {
    if (!query) return;

    const fetchData = async () => {
        setStatus('fetching');
        const response = await fetch(
            `https://hn.algolia.com/api/v1/search?query=${query}`
        );
        const data = await response.json();
        setData(data.hits);
        setStatus('fetched');
    };

    fetchData();
}, [query]);

return { status, data };

};`

  1. Or we should use redux or redux toolkit's middleware to do http or any async work and then dispatch an action in that middleware to update redux store.

for example:

CodePudding user response:

not exactly a stack overflow question, since it’s an opinion…

However, since it’s yet 2022, I would 100% got for RTKQ, https://redux-toolkit.js.org/rtk-query/overview

The benefits (small list):

  • cache
  • extraReducer
  • transformResponse
  • selectFromResults
  • automatic invalidation, refetching, polling
  • you can still use axios or gql

You don’t have to write all the logic yourself…

CodePudding user response:

Definitely an opinion type of question so take my answer with a grain of salt. But you should check out React Query. You can still use reducers for your redux store, just use React Query instead of your extra reducers.

https://react-query-v3.tanstack.com/

  • Related