Skip to main content

What does subscribe() do?

Definition

store.subscribe(listener) is a method of the Redux store that lets you subscribe to state changes.

In other words: every time the state (state) changes, your listener function (listener) is called.


In simple terms

subscribe() lets you "watch" for state changes in the store. When someone calls dispatch() and the reducer returns a new state, all subscribers get notified.


Example

javascript
import { createStore } from 'redux' // Reducer function counterReducer(state = { count: 0 }, action) { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 } default: return state } } // Create the store const store = createStore(counterReducer) // Subscribe to updates const unsubscribe = store.subscribe(() => { console.log('State changed:', store.getState()) }) // Dispatch an action store.dispatch({ type: 'INCREMENT' }) // -> "State changed: { count: 1 }" // Unsubscribe when you no longer need to watch unsubscribe()

How this works

  1. You call store.subscribe(listener) -> Redux adds this function to the list of subscribers.
  2. Every time dispatch() happens (when state actually changed) -> Redux calls all the listeners.
  3. Inside the listener you can:
  • call store.getState() and read the new state,
  • update the UI manually (if React isn't used),
  • or run some side logic.

Return value

subscribe() returns a function to unsubscribe:

javascript
const unsubscribe = store.subscribe(listener) unsubscribe() // stops watching for changes

In React this happens automatically

If you use React with Redux (via react-redux and Provider), then subscribe() is used inside connect() or useSelector().

So React components automatically re-render when the data from the store they're "watching" changes.

You don't call subscribe() manually - the library handles it.


Summary

MethodWhat it does
dispatch(action)Sends an action -> runs the reducer -> updates the state
getState()Returns the current state of the store
subscribe(listener)Subscribes a function to state updates
Return value of subscribe()A function to unsubscribe

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.