React-Redux Hooks
Now that you have a Redux store with actions and reducers, you need to connect it to your React components. The `react-redux` library provides hooks that make this connection simple and intuitive: `useSelector` and `useDispatch`.
Installation
npm install react-reduxProvider
First, wrap your app with the `` component and pass your Redux store to make it available to all components.
import { Provider } from 'react-redux';import store from './store';
function App() { return ( <Provider store={store}> <TodoApp /> </Provider> );}useSelector Reading State
The `useSelector` hook lets you extract data from the Redux store state. It takes a selector function that receives the state and returns the desired slice.
import { useSelector } from 'react-redux';
function TodoList() { const todos = useSelector(state => state.todos); return ( <ul> {todos.map(todo => ( <li key={todo.id}>{todo.text} - {todo.completed ? '✅' : '❌'}</li> ))} </ul> );}useDispatch Dispatching Actions
The `useDispatch` hook returns a reference to the dispatch function. You can use it to dispatch actions when needed.
import { useDispatch } from 'react-redux';import { addTodo } from './todoActions';
function AddTodo() { const [text, setText] = useState(''); const dispatch = useDispatch();
const handleSubmit = (e) => { e.preventDefault(); if (text.trim()) { dispatch(addTodo(text)); setText(''); } };
return ( <form onSubmit={handleSubmit}> <input value={text} onChange={(e) => setText(e.target.value)} /> <button type="submit">Add Todo</button> </form> );}Full Example
Combined, we get a working Redux-connected component:
function TodoApp() { const todos = useSelector(state => state.todos); const dispatch = useDispatch();
return ( <div> <AddTodo /> <ul> {todos.map(todo => ( <li key={todo.id}> {todo.text} <button onClick={() => dispatch({ type: TOGGLE_TODO, payload: { id: todo.id } })}> Toggle </button> </li> ))} </ul> </div> );}Two Minute Drill
- `react-redux` provides `Provider` to make the store available to all components.
- `useSelector` reads data from the store it subscribes to updates and re-renders when the selected slice changes.
- `useDispatch` gives you the dispatch function to send actions.
- These hooks replace the older `connect` API and are simpler to use.
Need more clarification?
Drop us an email at career@quipoinfotech.com
