React js

React Redux In React

React Redux: What & Why?

  • React Redux lets React components read data from a Redux store and dispatch actions to update it.

  • It provides hooks and components to efficiently connect Redux with React.

  • Simplifies your app’s state management and UI synchronization.


Key Concepts & API

1. <Provider>

  • Wrap your app with <Provider> and pass the Redux store.

  • Makes the store available to all nested components.

jsx
import { Provider } from 'react-redux';

<Provider store={store}>
<App />
</Provider>


2. useSelector

  • A hook to read state from the Redux store.

  • Accepts a selector function to pick the part of the state you want.

jsx
import { useSelector } from 'react-redux';

const count = useSelector(state => state.count);


3. useDispatch

  • A hook to dispatch actions to the store.

jsx
import { useDispatch } from 'react-redux';

const dispatch = useDispatch();
dispatch({ type: 'INCREMENT' });


Complete Example: Counter

jsx
import React from 'react';
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';

// Reducer
const reducer = (state = { count: 0 }, action) => {
switch(action.type) {
case 'INCREMENT': return { count: state.count + 1 };
default: return state;
}
};

const store = createStore(reducer);

// Counter component
function Counter() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();

return (
<>
<h1>{count}</h1>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
</>
);
}

// App component
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}

export default App;


Summary

Feature What it does
<Provider> Makes Redux store available to components
useSelector Reads state from the Redux store
useDispatch Dispatches actions to update the state

Leave a Reply

Your email address will not be published. Required fields are marked *