Redux State
In React there are two kinds of components: those that are aware of and respond to state changes, called stateful containers, and those that only render the data supplied to them, called stateless components. This does not change when using Redux — it actually makes it easier. Both of these things necessary to get these libraries working well together can be placed in a stateful component — the only kind that knows about Redux.
Making the store available
Stateful components will exist inside of stateless components and visa versa for potentially many layers deep. We don't want to have to pass the Redux store through all of the layers — especially if they aren't going to use it. The react-redux package provides the Provider component that makes the store available to all containers regardless of their location in the hierarchy.
import { Provider } from 'react-redux'import store from './store'const root = createRoot(document.getElementById('app'))root.render(<Provider store={store}><MyRootComponent /></Provider>)
State change notifications
The first thing we listed above that needs to happen to use these libraries together is for React components to be re-rendered during Redux state changes. The react-redux package provides the useSelector() hook for this very reason. In our stateful containers, we pass useSelector a function. That function will be given the redux state and should return the information we want to use. useSelector must be used within the main code block of our component (not in sub functions or outside the component).
import { useSelector } from 'react-redux'function MyComponent (){const data = useSelector(reduxState => reduxState.data)return <><h1>My data!</h1><p>{data}</p></>}
In the function that we give to useSelector(), we know it will be passed the Redux global state (and can name the variable whatever we wish) and can therefore return any information contained within that state. In the example above we have a data property within our state and, once selected, it is assigned to our constant variable. We can then use this variable in our component.
Dispatching Redux actions from React Components
To send actions to Redux and update our Redux state, we use the react-redux hook useDispatch. The useDispatch hook is used in a similar way to useSelector, though the two do quite different things. The useDispatch function must be used within the main code block of the component and will then give us access to the dispatch function.
import { useDispatch } from 'react-redux'import { showDetails } from '../actions'function MyComponent (props) {const dispatch = useDispatch()const handleClick = () => {dispatch(showDetails(props.id))}return <><button onClick={handleClick}>Show details for {props.name}</button></>}
Now when our handleClick function is called it will pass the props.id to our action creator and the action it returns will be dispatched to the Redux store.