0
0
React Nativemobile~5 mins

Redux selectors in React Native

Choose your learning style9 modes available
Introduction

Redux selectors help you get specific data from your app's state easily and clearly.

When you want to get user info from the app state to show on the screen.
When you need to get a list of items filtered by some rule.
When you want to avoid repeating code to get the same data in many places.
When you want to keep your components simple and focused on showing UI.
When you want to improve app performance by avoiding unnecessary updates.
Syntax
React Native
const selectData = (state) => state.someSlice.data;
Selectors are simple functions that take the whole state and return a part of it.
You can create selectors to get any piece of data you need from the Redux store.
Examples
This selector gets the user's name from the user slice of the state.
React Native
const selectUserName = (state) => state.user.name;
This selector returns only the tasks that are marked as completed.
React Native
const selectCompletedTasks = (state) => state.tasks.filter(task => task.completed);
This uses createSelector to memoize the filtered tasks, improving performance.
React Native
import { createSelector } from '@reduxjs/toolkit';

const selectTasks = (state) => state.tasks;
const selectCompletedTasks = createSelector(
  [selectTasks],
  (tasks) => tasks.filter(task => task.completed)
);
Sample App

This React Native component uses a Redux selector to get the user's name from the state and shows it in a friendly greeting.

React Native
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>
  );
}
OutputSuccess
Important Notes

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.

Summary

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.