Selector Functions with Redux Toolkit
Showcase how selector functions are used in conjunction with Redux Toolkit's createSlice and useSelector hooks to efficiently derive data from the Redux store with memoization.
import { createSlice, createSelector } from '@reduxjs/toolkit';
// Redux state slice with initial state and reducers
const userSlice = createSlice({
name: 'user',
initialState: {
entities: [],
loading: false,
},
reducers: {
// Reducers here
},
});
// Export actions if needed
// export const { action1, action2 } = userSlice.actions;
export default userSlice.reducer;
This piece of code defines a Redux state slice named 'user' using the createSlice function from Redux Toolkit. It has an initial state with 'entities' and 'loading' properties and a placeholder for reducer functions.
// Selector without memoization
export const selectAllUsers = state => state.user.entities;
// Memoized selector using createSelector from Redux Toolkit
c// It only recalculates when entities change
cexport const selectUserById = createSelector(
[selectAllUsers, (state, userId) => userId],
(users, userId) => users.find(user => user.id === userId)
);
This code snippet exports selectors for the user state. 'selectAllUsers' is a basic selector that returns all user entities. 'selectUserById' is a memoized selector which will only recompute the result if the users or the userId arguments change, thus saving on unnecessary recalculations.
import React from 'react';
import { useSelector } from 'react-redux';
import { selectUserById } from './userSlice';
// Component that uses the useSelector hook to get a user by ID
function UserDetails({ userId }) {
// useSelector will re-render the component only when the specified user changes
const user = useSelector(state => selectUserById(state, userId));
return (
<div>
<h3>User Details</h3>
{user ? (
<p>Name: {user.name}</p>
) : (
<p>User not found</p>
)}
</div>
);
}
This piece of code shows a React functional component that uses the useSelector hook to access the Redux store and get data for a specific user by ID using a memoized selector. The component will only rerender if the selected user's data changes in the Redux store.