Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it correct or good practice to use SWR together with Redux?

I'm using the SWR

In my code I am using the junction of both as follows

const vehiclesStates = useSelector(({ vehiclesStates: state }) => state); // REDUX
const response = useFetch("/vehicles/states") // SWR
const dispatch = useDispatch(); // REDUX

// REDUX
useEffect(() => {
  if(response.data) dispatch(VehiclesStatesActions.setVehiclesStates(response.data.result))
}, [response.data, dispatch]);

if(response.error) return <div>ERROR - {response.error.toString()}</div> // SWR
else if(!response.data) return <div>LOADING</div> // SWR

// If there is a return I render my component
return (<></>)

In this excerpt above I set my component state in redux with the data that I return using the SWR (Integrated with axios). That way, in any other component that needs to use that same data, I only import it with redux's useSelect.

This way

const vehiclesStates = useSelector(({ vehiclesStates: state }) => state);

I find it more practical than just using the SWR by calling useFetch on each component that wants to use that data.

My question is: Is using this way a correct way, or can it affect performance or something?

Thanks in advance

like image 680
Alexssander Leal Luz Avatar asked Dec 18 '20 21:12

Alexssander Leal Luz


1 Answers

I think that's a little redundant, you could be better using one or the other, SWR is intended to use the cache as a local state, because that state lives on the server it's more adecuated and frees you from managing every manipulation in the state verbosely, like you have to do with redux explicitly calling API calls anytime you dispatch an action.

Using both kinds of defeat the purpose of SWR, you'll be better just using Redux then. A good rule to follow is to use SWR to manage the state that lives in the server, and Redux to manage the local state.

Some scenario where I can see both coexisting, it's when you have a very complex data manipulation, and you have to modify and delete information too often, I think that case will use some mix of redux and the mutate function of SWR.

like image 173
Tlacaelel León Villaseñor Avatar answered Sep 21 '22 00:09

Tlacaelel León Villaseñor