In a React App designed using mostly hooks. I don't see the need for the redux-thunk middleware, or am I missing something?
Redux-thunk approach
const Component = () => {
const dispatch = useDispatch()
const user = useSelector(state => state.user)
useEffect(() => {
dispatch(getUserFromApiAndDispatch())
}, [])
return <div>{user}</div>
}
Or just simply
const Component = () => {
const dispatch = useDispatch()
const user = useSelector(state => state.user)
useEffect(() => {
getUserFromApi().then(({data}) => dispatch({type: 'SET_USER'; payload: data.user})
}, [])
return <div>{user}</div>
}
CodePudding user response:
It depends. Of course, you can do all that without thunks. Getting the current state asynchronously would be a bit more dirty (in a thunk you can just call getState
) but it is doable.
The question is: what do you lose?
And you lose mainly a concept. The strength of Redux itself is that it creates a data flow outside of your components. Your components just dispatch an event, and logic outside the component happens. Your component later gets a new state and displays it.
By pulling stuff like data fetching into your component, you lose that benefit. Instead of a store that does it's thing and components that do their thing, you now have components that need to know about the data layer and about store internals (in cases where many different actions should be dispatched in a given order).
Logic moved back into your components and you get a mess.
If you just use a thunk, all your component does is dispatch(userDetailsPageDisplayed({ userId: 5 }))
and after a while, it gets all the data.
Going a little bit off-topic: you are writing a very outdated style of Redux here. Modern Redux does not use switch..case reducers, immutable reducer logic or ACTION_TYPES. Also you should usually not build dispatched actions in the component. I'd recommend you to read the official Redux tutorial. And then maybe give the Redux Style Guide a read, for more context and recommendations (we recommend event-type actions, not setter-style ones for example).
CodePudding user response:
Actually no. redux-thunk is just a convention of handling asynchronous tasks. You can easily do that with function or methods. Back in the days, when react only had class based components, it was not possible to use a functionality multiple times in our application. But this problem got solved with Stateful Function Components and Hooks. So, you really don't need thunk.