Pruthvi
Pruthvi

Reputation: 89

Will Redux in React work only with Functional Components?

I have been doing some learning of React and have been developing projects. I recently started of with Redux, and so, wanted to develop my next project using it. I set it up perfectly fine, and for one component in the app, I thought, why can't I have a class component in it. I tried the same and it threw up a lot of errors.

So I want to know, will react-redux only work with functional components and not class components. and if so, it would be great if you can explain why?

For example: I can't seem to declare the selectors inside the class component. When I declare a variable as follows:

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

It throws the following error:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

Upvotes: 1

Views: 799

Answers (1)

bilwit
bilwit

Reputation: 819

You eventually got the gist of it in the comments but to to put it simply, you can use Redux with either class or functional components, but the way you access it use different methods.

Functional Components: useSelector, useDispatch https://react-redux.js.org/api/hooks

import { useSelector } from "react-redux";
import { myAction } from './myActions';

const MyComponent = (props) => {
  // connect to "play" from Redux store
  const play = useSelector((state) => state.play);
  // do stuff
  console.log(play);
}

export default MyComponent;

Class Components: connect(mapStateToProps, mapDispatchToProps) https://react-redux.js.org/api/connect

import { connect } from "react-redux";

class MyComponent extends React.Component {
  // do stuff
  console.log(this.props.play)
}

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

export default connect(mapStateToProps)(MyComponent);

Upvotes: 2

Related Questions