Introduction
Redux selectors help you get specific data from your app's state easily and clearly.
Redux selectors help you get specific data from your app's state easily and clearly.
const selectData = (state) => state.someSlice.data;
const selectUserName = (state) => state.user.name;
const selectCompletedTasks = (state) => state.tasks.filter(task => task.completed);createSelector to memoize the filtered tasks, improving performance.import { createSelector } from '@reduxjs/toolkit'; const selectTasks = (state) => state.tasks; const selectCompletedTasks = createSelector( [selectTasks], (tasks) => tasks.filter(task => task.completed) );
This React Native component uses a Redux selector to get the user's name from the state and shows it in a friendly greeting.
import React from 'react'; import { View, Text } from 'react-native'; import { useSelector } from 'react-redux'; // Simple selector to get user name const selectUserName = (state) => state.user.name; export default function UserNameDisplay() { const userName = useSelector(selectUserName); return ( <View style={{ padding: 20 }}> <Text accessibilityRole="header" style={{ fontSize: 20, fontWeight: 'bold' }}> Hello, {userName}! </Text> </View> ); }
Selectors help keep your components clean by separating data access from UI code.
Using memoized selectors with createSelector can improve performance by avoiding unnecessary recalculations.
Always name selectors clearly to show what data they return.
Redux selectors are functions to get specific data from the app state.
They make your code easier to read and reuse.
Memoized selectors help your app run faster by caching results.
selectUser that returns state.user?state parameter.state.user directly. Arrow function with implicit return is correct.const selectCompletedTodos = state => state.todos.filter(todo => todo.completed); and the state { todos: [{id:1, completed:true}, {id:2, completed:false}, {id:3, completed:true}] }, what will selectCompletedTodos(state) return?completed is true.completed:true, so they are included.const selectUserName = state => { state.user.name }return to return state.user.name.reselect to get the count of completed todos from state. Which code correctly implements this?createSelector function is imported from 'reselect' and used properly.selectTodos gets todos array; output function filters completed and counts them.const selectCompletedCount = state => state.todos.filter(todo => todo.completed).length is not memoized; importing createSelector from 'redux' is wrong; todos => todos.completed.length accesses property incorrectly.Pass the test and this pattern moves unknown