I'm a bit new to hooks, and I'm using a pattern I don't know is desirable or not. What I'm doing is mixing redux with useEffect hooks in a way that for every meaningful state change one of my hooks is triggered and update some state.
For example If I have a error field in my reducer. I write something like this.
useEffect(() => {
if(state.error && !state.error.open) {
showSnackbar(state.error.text)
}
}, [state.error])
and I clear error when user dismiss snackbar.
Or
If I want to react to a button click with some data fetching and changing page I use:
(The reason I'm explicitly setting user clicked is when user clicks on back button in the next page, I'm not redirected to the page again as data is still present in store.)
useEffect(() => {
if(buttonClicked && state.someData.id > 0) {
history.push('/route');
}
}, [state.someData, buttonClicked]);
handleClick = () => {
dispatch(actions.fetchSomeData());
setUserClicked();
}
In my component sometimes I have 7-8 useEffects handling different things, and most of them have conditional behavior.
Lots of the time I see code like this:
const result = await dispatch(someAction);
if (result.payload.error)
{
//...
}
else
{
history.push(...);
}
Does this pattern have some advantage over using multiple lifecycle hooks?
Maybe I use the first way beacuse it feels more declarative? But is it good to have many useEffects? In the above code I handled error and success in two hooks.
Thanks.
preventDefaulton the button onClick event may help you. The second pattern is something I see used more with asynchronous redux actions, like API calls to fetch data, usually with middleware like Thunks (redux-thunk), but this is usually to allow returning errors directly back to the UI while having the request fetching/processing logic decoupled from the component code.