tezvyn:

React Redux: Connecting Components to a Global Store

AI-drafted, machine-checkedSource: react-redux.js.orgintermediate

React Redux connects your React UI to a global Redux state store, letting components read data and dispatch updates. It's used to avoid "prop drilling" shared state across the app.

WHY IT EXISTS: React's built-in state is local to components. For complex apps, sharing state like user info across many components requires passing props through many layers, a tedious process called "prop drilling". Redux offers a central "store" for this state, but connecting components to it requires boilerplate subscription logic.

THE MENTAL MODEL: Think of React Redux as the official plumbing between your React components (the "faucets") and the central Redux state store (the "water main"). It provides the Provider component to make the store available globally and hooks like useSelector and useDispatch to let any component tap into the state or send updates back to the store.

HOW IT WORKS: You wrap your entire application in a <Provider store={store}> component, making the Redux store accessible to any nested component. Inside a component, you use the useSelector hook to extract specific pieces of data from the store. React Redux subscribes your component to the store and re-renders it only when the selected data changes. To update the state, you use the useDispatch hook to get a dispatch function, which you then call with a Redux action.

WHEN TO USE IT: Use React Redux when you have significant amounts of application state that are needed by many components at different levels of your component tree. It's ideal for managing user authentication status, theme data, or complex API data that multiple parts of the UI need to display or modify.

WHEN NOT TO USE IT: Avoid Redux for state that is truly local to a single component, like a form input's value or whether a dropdown is open. Using React's own useState for local state is simpler. Overusing Redux for everything adds unnecessary complexity and boilerplate, a common anti-pattern.

ONE CANONICAL EXAMPLE: A component displaying the current user's name would use const userName = useSelector(state => state.user.name) to read it from the store. A login button would use const dispatch = useDispatch() and then call dispatch({ type: 'user/login', payload: userData }) on click. The component showing the name re-renders automatically when the store is updated.

Read the original → react-redux.js.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.