- How to fetch data with React Hooks?
- fetch using useState()
- Always use useReducer() to fetch data
- Reducer for sync - only for state changes
- Reducer for async - side effects and fetch
- Component
- Full code
- Source
How to fetch data with React Hooks?
You will mostly end-up with Robin’s blog post regarding the fecth method. But the problem using useState() is that we can’t execute any other code after fetch success.
for an example:- do one fetch, if that fetch is successfull then call some JavaScript like clear the form using useState(), if fails display error message. That’s somehow difficult if we use useState().
fetch using useState()
I created a codesandbox based on best practices to fetch data using hooks. Please feel free to update the script to make some Js after the fetch.
in that codesandbox, try to execute some Js after the fetch. It won’t work becase it’s sync code.
Always use useReducer() to fetch data
I am not big fan of useState() method due to it’s nature. I decided to use only useReducer() to fetch data and async operations. It’s same like Redux style.
- Create two useReducer()
- one for sync and the other for async (ajax and side effects)
- use the async reducer as a main and call the other reducer inside.
- if you see the code, you can easily understand
Reducer for sync - only for state changes
1 | function reducer(state, action) { |
Reducer for async - side effects and fetch
1 | function dispatchMiddleware(dispatch) { |
Component
1 | export default function Users() { |
Full code
1 | import React, { useReducer } from "react"; |
The full code is available in the codesandbox