The useSelector
hook is a part of the react-redux
library, which is commonly used with Redux to extract data from the Redux store in a React component. Let's walk through an example of using useSelector
:
Assuming you have a Redux store set up with a simple counter reducer:
// counterReducer.js
const counterReducer = (state = { count: 0 }, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
};
export default counterReducer;
And your store configuration:
// store.js
import { createStore } from 'redux';
import counterReducer from './counterReducer';
const store = createStore(counterReducer);
export default store;
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import store from './store.js
import { App } from './App'
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
<Provider store={store}>
<App />
</Provider>
)
Now, you can use useSelector
in a React component to access the state from the Redux store:
// CounterComponent.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
const CounterComponent = () => {
// Using useSelector to access the count state from the Redux store
const count = useSelector(state => state.count);
// Using useDispatch to get the dispatch function
const dispatch = useDispatch();
// Example functions to dispatch actions
const increment = () => {
dispatch({ type: 'INCREMENT' });
};
const decrement = () => {
dispatch({ type: 'DECREMENT' });
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
export default CounterComponent;
In this example:
useSelector
is used to select a part of the Redux state (in this case, thecount
property) in theCounterComponent
.useDispatch
is used to get thedispatch
function, which is then used to dispatch actions to the Redux store.- The
increment
anddecrement
functions dispatch actions to update the state in the Redux store.
This is a simple example, and in a larger application, you might have multiple selectors for different parts of the state. useSelector
helps you connect specific pieces of your Redux state to your React components, making it easy to react to changes in your application state.