how can i use react redux in class component?

484 Views Asked by At

im a new to redux, and i want to know if it possible to use redux in class component. we know that hooks works only in function component, so i export a function to use useSelector to access the store :

import { useSelector, useDispatch } from "react-redux";

export default function Selector() {
  const counter = useSelector((state) => state.counter);
  return counter;
}

and import it to the compone component so will be like this:

import React, { Component } from "react";
import selector from "../Store/selector";

export class Compone extends Component {
  componentDidMount() {
    console.log(selector());
  }
  render() {
    return (
      <>
        <h1>
          Counter: <span>0</span>
        </h1>
        <button style={{ marginRight: "10px" }}>Increase</button>
        <button>Decrease</button>
      </>
    );
  }
}

export default Compone;

and i import compone component to the App root component:

import React, { Component } from "react";
import Compone from "../components/compone/Compone";
export class App extends Component {
  render() {
    return (
      <div>
        <Compone />
      </div>
    );
  }
}

export default App;

so this didn't work for me, is there a way to use redux in class component?,

how to use redux in class component, how to use react redux in class component,

1

There are 1 best solutions below

2
ClassHacker On

First of all you have to create some actions and some reducers.
Then you need to create a store using the reducers.
After that you can use connect method of react-redux with your class component.