I'll never forget the project that made me question my sanity. The previous developer had used Redux Toolkit, which I had never worked with before. My past experiences with Redux involved tedious switch cases, leaving me with PTSD. I dreaded dealing with it again.
When the developer announced their departure, I saw an opportunity to refactor the code to use TanStack Query, a library I was more comfortable with. However, the tight deadline forced me to reconsider. I decided to face my fears and learn Redux Toolkit.
As I delved into the code, I discovered the strengths of both libraries. Redux Toolkit's organization and TanStack Query's storage features impressed me. I realized that, with the right mindset, I could master both.
Here's a comparison of common actions in Redux Toolkit and TanStack Query:
- Data Fetching
Redux Toolkit:
// Create an async thunk
export const fetchUsers = createAsyncThunk(
'users/fetchUsers',
async () => {
const response = await axios.get('/users');
return response.data;
}
);
// Use the thunk in a component
dispatch(fetchUsers());
TanStack Query:
// Create a query client
const queryClient = new QueryClient();
// Fetch data with the useQuery hook
const { data, error, isLoading } = useQuery(
'users', // key
async () => {
const response = await axios.get('/users');
return response.data;
}
);
- Data Caching
Redux Toolkit:
// Use the createEntityAdapter
to manage cached data
const usersAdapter = createEntityAdapter();
const usersSlice = createSlice({
name: 'users',
initialState: usersAdapter.getInitialState(),
reducers: {
// ...
},
});
TanStack Query:
// Use the QueryClient
to cache data
queryClient.setQueryData('users', data);
- Data Updating
Redux Toolkit:
// Create an async thunk to update data
export const updateUser = createAsyncThunk(
'users/updateUser',
async (userData) => {
const response = await axios.put(/users/${(link unavailable)}
, userData);
return response.data;
}
);
TanStack Query:
// Use the useMutation
hook to update data
const { mutate, isLoading } = useMutation(
async (userData) => {
const response = await axios.put(/users/${(link unavailable)}
, userData);
return response.data;
}
);
In conclusion, both Redux Toolkit and TanStack Query have their strengths. By embracing both libraries, I transformed my project experience from a nightmare to a success story. Don't be afraid to explore new tools – you never know what you might discover!
Top comments (0)