How to use a Simple Selector Function In Redux
In this approach, we directly access the users from the Redux store without any optimization. We retrieve the list of users and display them in a component. This method works fine for small-scale applications, but it may lead to performance issues as the application grows.
Example: This example uses the simple selector function to retrieve specific pieces of state using selectors.
// App.js
import React from 'react';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
// Define initial state
const initialState = {
users: [
{ id: 1, name: 'Rajveer', isActive: true },
{ id: 2, name: 'Malhotra', isActive: false },
{ id: 3, name: 'Veer', isActive: true },
// Add more users as needed
],
};
// Define reducer function
const reducer = (state = initialState, action) => {
// For simplicity, we're not
// handling any actions in this example
return state;
};
// Create Redux store
const store = createStore(reducer);
// Define UserList component
const UserList = ({ users }) => {
return (
<div>
<h2>All Users</h2>
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
};
// Connect UserList component to Redux store
const ConnectedUserList = () => (
<Provider store={store}>
<UserListContainer />
</Provider>
);
// Map state to props for UserList component
const UserListContainer = () => {
const state = store.getState();
const users = state.users;
return <UserList users={users} />;
};
// App component
const App = () => {
return (
<div>
<h1>Basic Selector</h1>
<ConnectedUserList />
</div>
);
};
export default App;
Output:
Different ways to retrieve specific pieces of state using selectors
In Redux applications, selectors are functions that facilitate the retrieval of specific pieces of state from the Redux store. Selectors play a crucial role in decoupling components from the store’s structure and improving performance by memoizing computed values. Let’s explore two approaches to retrieving specific states using selectors.