Before you start, please make sure that you have correctly installed Redux and its related dependencies (such as redux, react-redux, etc.), and have also created the data store, actions, and reducers. How to use store in React
1. React Class Components and Redux#
First, you need to connect your component to Redux using the connect higher-order component. The two main parameters of connect are mapStateToProps and mapDispatchToProps. mapStateToProps is used to select the desired state fragments from the Redux store and map them to the component's props. mapDispatchToProps is used to associate the created action creators with the component's props. Here is a simple example:
// First, import the dependencies:
import React from 'react';
import { connect } from 'react-redux';
import { sampleActionCreator } from './actions';
// Then, the class component:
class SampleComponent extends React.Component {
onButtonClick = () => {
this.props.sampleActionCreator();
};
render() {
const { dataFromReduxStore } = this.props;
return (
<div>
<button onClick={this.onButtonClick}>Trigger Redux Action</button>
<p>Data from Redux store: {dataFromReduxStore}</p>
</div>
);
}
}
// Next, connect the component to Redux:
const mapStateToProps = (state) => ({
dataFromReduxStore: state.sampleReducer.data,
});
const mapDispatchToProps = {
sampleActionCreator,
};
export default connect(mapStateToProps, mapDispatchToProps)(SampleComponent);
2. React Functional Components and Redux#
In functional components, you can use the useSelector and useDispatch hooks provided by react-redux to connect to Redux.
// First, import the dependencies:
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { sampleActionCreator } from './actions';
// Then, the functional component:
const SampleComponent = () => {
const dataFromReduxStore = useSelector((state) => state.sampleReducer.data);
const dispatch = useDispatch();
const onButtonClick = () => {
dispatch(sampleActionCreator());
};
return (
<div>
<button onClick={onButtonClick}>Trigger Redux Action</button>
<p>Data from Redux store: {dataFromReduxStore}</p>
</div>
);
};
export default SampleComponent;
The above is the method of using Redux in React class components and functional components. The main difference between these two methods is that they use different patterns (class components use the connect higher-order component and mapStateToProps/mapDispatchToProps, while functional components use the useSelector and useDispatch hooks) to achieve state selection and action creator functionality.