useSelector
- React Native course
- Advanced
- Lesson 53/83
- 5 min
Learn to read state with useSelector.
useSelector
useSelector is a hook used to read state from the store. It takes a selector function: const count = useSelector((state) => state.counter). This function takes the store state and returns the relevant part. When state changes the component re-renders.
The value returned by the selector becomes the variable in the component. Selecting only the needed field is important for performance: returning the whole state.counter instead of (state) => state.counter.value triggers a wider re-render. Writing fine-grained selectors reduces unnecessary renders.
Writing the selector
The selector function returns the field you want to read. state.counter is the whole counter slice; state.counter.value gives only the value. The second is more efficient; only a value change triggers a render. In the first form, another field of the slice changing also triggers a render.
In the component you write const count = useSelector((state) => state.counter.value) and display count with <Text>{count}</Text>. Whenever state changes useSelector returns the new value; the component updates. This pattern repeats in every Redux read.
Practice Write CounterValue
Complete the CounterValue component. Import useSelector from react-redux. Read the value with const count = useSelector((state) => state.counter.value). Return <Text>{count}</Text>.
Starter code
import React from 'react';
import { Text } from 'react-native';
export function CounterValue() {
// read count with useSelector and show inside Text
return null;
}Sample solution
import React from 'react';
import { Text } from 'react-native';
import { useSelector } from 'react-redux';
export function CounterValue() {
const count = useSelector((state) => state.counter.value);
return <Text>{count}</Text>;
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the useSelector parts
| Term | Meaning |
|---|---|
useSelector |
Reads state |
(state) => state.counter |
Selector function |
state.counter |
Counter value |
re-render |
Happens on state change |
2 Write the selector function
const count = useSelector((state) => state.____.value);
const count = useSelector((state) => state.counter.value);
Explanation: counter is the slice name.
3 Why is a fine-grained selector preferred?
- It reduces unnecessary renders
- It changes styles
- It speeds up animation
- It deletes the token Correct answer
Explanation: A fine-grained selector only re-renders when the relevant field changes.