I am new to React and Redux and as we know, it is best to use class component for those components that have state and the question I would like to ask is that Is it recommended to use functional component for components that have connection and interaction with Redux store since those components that interact with store do not have state locally.
As of version 7.x react-redux now has hooks for functional components
const store = useSelector(store => store)
So that we can use functional component with redux store like class component.
please check below link to get more idea about hooks
https://react-redux.js.org/next/api/hooks
It's perfectly fine to connect functional components to redux store.
Functional components don't have a state is not completely correct with hooks. You can add state to functional component with hooks.
Answering your question, you can connect functional component with redux store like below.
import React from "react";
import ReactDOM from "react-dom";
import { createStore } from "redux";
import { Provider, connect } from "react-redux";
const reducers = (state = 0, action) => {
switch (action.type) {
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
default:
return state;
}
};
const store = createStore(reducers, 0);
const App = ({ count, handleIncrement, handleDecrement }) => {
return (
<div>
<button onClick={handleIncrement}>+</button>
<h4>{count}</h4>
<button onClick={handleDecrement}>-</button>
</div>
);
};
const mapStateToProps = state => {
return { count: state };
};
const mapDispatchToProps = dispatch => {
return {
handleIncrement: () => {
dispatch({ type: "INCREMENT" });
},
handleDecrement: () => {
dispatch({ type: "DECREMENT" });
}
};
};
const ConnectedApp = connect(
mapStateToProps,
mapDispatchToProps
)(App);
ReactDOM.render(
<Provider store={store}>
<ConnectedApp />
</Provider>,
document.getElementById("root")
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With