Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

357
Views
Can I use dispatch() in class component?

I want to use dispatch() in class component

import React from "react";
import { connect } from "react-redux";
import { useDispatch } from "react-redux";
import {toDo} from "../patials/user";

class SignUp extends React.Component {
  constructor(props) { 
    super(props);
    this.onHandle = this.onHandle.bind(this);
  }
  
 onHandle() {
   const dispatch = useDispatch();
   dispatch(toDo());
 }
render() {
  return(
   <button onClick={onHandle}>Action</button>
  );
}
} 
export default connect()(SignUp)

I got the error: React Hook "useDispatch" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You cannot use useDispatch in a react class component, for the class component you need to map dispatch to props and use it like the following

// components/AddTodo.js

import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../redux/actions'

class AddTodo extends React.Component {
  // ...

  handleAddTodo = () => {
    // dispatches actions to add todo
    this.props.addTodo(this.state.input)

    // sets state back to empty string
    this.setState({ input: '' })
  }

  render() {
    return (
      <div>
        <input
          onChange={(e) => this.updateInput(e.target.value)}
          value={this.state.input}
        />
        <button className="add-todo" onClick={this.handleAddTodo}>
          Add Todo
        </button>
      </div>
    )
  }
}

export default connect(null, { addTodo })(AddTodo)



about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!