0
0
ReactHow-ToBeginner · 3 min read

How to Use useSelector in React: Simple Guide with Examples

In React, use the useSelector hook to read data from the Redux store by passing a selector function that picks the needed state. It lets your component subscribe to store updates and re-render when the selected state changes.
📐

Syntax

The useSelector hook takes a function called a selector that receives the entire Redux store state and returns the part your component needs. It subscribes your component to that part of the state.

Example parts:

  • const value = useSelector(selectorFunction): calls the hook
  • selectorFunction(state): returns the desired slice of state
javascript
const value = useSelector(state => state.someValue);
💻

Example

This example shows a React component using useSelector to get a count value from the Redux store and display it.

javascript
import React from 'react';
import { useSelector } from 'react-redux';

function CounterDisplay() {
  const count = useSelector(state => state.counter.value);
  return <div>Current count: {count}</div>;
}

export default CounterDisplay;
Output
Current count: 0
⚠️

Common Pitfalls

1. Not wrapping your app with Provider: The Redux store must be provided to React components using <Provider store={store}>. Without it, useSelector will fail.

2. Selecting too much state: Selecting large or unnecessary parts of the state can cause extra re-renders. Select only what you need.

3. Mutating state inside selector: Never change state inside the selector function; it should be pure and only return data.

javascript
/* Wrong: selecting entire state causes extra renders */
const allState = useSelector(state => state);

/* Right: select only needed slice */
const count = useSelector(state => state.counter.value);
📊

Quick Reference

ConceptDescription
useSelector(selector)Reads data from Redux store using selector function
selector(state)Function that returns needed slice of state
Re-renderComponent re-renders when selected state changes
ProviderWrap app with to enable useSelector
Avoid selecting too muchSelect only necessary state to optimize performance

Key Takeaways

Use useSelector to read specific parts of Redux state in React components.
Pass a selector function that returns only the needed slice of state.
Wrap your app with Provider to supply the Redux store.
Avoid selecting large state slices to prevent unnecessary re-renders.
Keep selector functions pure and do not mutate state inside them.