Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use react-redux useSelector in class component?

I am new in react and trying to learn redux. I want to access the store inside a class, but it gives me an error the I cant use hook in class.

When I use this code in function (as I saw in a YouTube tutorial), it works without any problem. Here I access to counter in the store.

 function App() {       const counter = useSelector(state => state.counter);            return <div>{counter}</div>;     } 

but when I want to do this in class, it gives me an error that I can't use hooks in class.

So how can I access to my store either useSelector or useDispatch in class component?

like image 567
morteza Avatar asked Jul 21 '19 18:07

morteza


People also ask

Can we use react Redux in class component?

Redux is a library that allows a React app to create a global state object that can be used in any component across the app by consuming the state object.

Where is useSelector used?

If you want to retrieve multiple values from the store, you can: Call useSelector() multiple times, with each call returning a single field value. Use Reselect or a similar library to create a memoized selector that returns multiple values in one object, but only returns a new object when one of the values has changed.

Can we use Redux in functional component?

No worries, you can still use the older connect Higher Order Component to inject your redux state and dispatchable actions into the props passed to the component.


1 Answers

As @Ying Zuo said, your method works only with Functional Components. To solve this problem:

Instead of this line:

const counter = useSelector(state => state.counter); 

You define the counter state like this:

const mapStateToProps = state => ({     counter: state.counter }); 

Then for dispatching you should use it like this:

const mapDispatchToProps = () => ({      increment,      decrement }); 

At the end you combine everything like this:

export default connect(     mapStateToProps,     mapDispatchToProps() )(App); 

Don't forget to import increment and decrement from your action and connect from the react-redux module.

like image 166
Medanko Avatar answered Oct 04 '22 14:10

Medanko