Redux - React Integration (react-redux)

Connect React to Redux

Use <Provider store> to make the store available, then read with useSelector and update with useDispatch.

Try it: Counter with react-redux

View source
const { createStore } = Redux;
const { Provider, useSelector, useDispatch } = ReactRedux;
function reducer(state={ value:0 }, action){
  if (action.type==='inc') return { value: state.value+1 };
  if (action.type==='dec') return { value: state.value-1 };
  return state;
}
const store = createStore(reducer);
function Counter(){
  const value = useSelector(s => s.value);
  const dispatch = useDispatch();
  return (
    <div>
      <div>Value: {value}</div>
      <button onClick={() => dispatch({type:'inc'})}>+1</button>
      <button onClick={() => dispatch({type:'dec'})} style={{marginLeft:8}}>-1</button>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('react-redux-root')).render(
  <Provider store={store}>
    <Counter />
  </Provider>
);

Syntax primer

  • Provider exposes the store to descendant components.
  • useSelector(selector) reads from the store; subscribes and un-subscribes automatically.
  • useDispatch() returns the store’s dispatch function.