React - Incorrect use of hooks and class components

Understanding hooks as the opposite of a class component can be confusing. A simple line of code can trigger an error when trying to adapt it for use in a class component. Take, for example, this situation: .jsx files and functional components work seamlessly with a given piece of code.

Explore Codesandbox example one

This particular piece of code showcases a straightforward method of sharing state between components. The concept is demonstrated through two key files: extendDiv, responsible for managing the state and its modification, and a separate file called global, designed to propagate that state across all components - specifically, a "son" (filho) and "father" (pai).

Although everything works smoothly in the Codesandbox example one, attempting to replicate the same functionality with a class component in the App.jsx along with some TypeScript files leads to an error message:

global.isDivExtended = extendDiv();
//Invalid hook call. Hooks can only be called inside of the body of a function component.

To delve deeper into this issue, feel free to explore the complete code and experiment further using Codesandbox example two. If you're seeking solutions on how to make this setup function within a class component context, attempts to bind global or leverage this have been made without success. Any insights provided would be greatly appreciated. Thank you.

Answer №1

Avoid calling React hooks from within class components.

To resolve this issue, you have two options: either convert your class component to a function component and utilize hooks for managing state, or stick with the class component and manage state using class-component methods. The preferred approach is to convert to a function component.

Although I cannot confirm due to missing files in the sandbox, it is likely that the following code snippet could work:

import * as React from "react";
import "./styles.css";
import Father from "../src/components/father";
import global from "./global";
import extendDiv from "./extendDiv";

function App(props) {
  let [dateVar, setDateVar] = React.useState({ date: new Date() })
  global.isDivExtended = extendDiv();

  return (
      <>
        <Father></Father>
      </>
  )
}

export default App;

Alternatively, consider creating a higher-order component wrapper for your hook logic. This way, you can pass the hook's functionality as a prop to your class component. More information on this approach can be found here. However, it is advised to avoid this method if possible as it can lead to confusion and make testing more difficult. Function components are considered the future of React and provide a more enjoyable coding experience.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the significance of utilizing generic types as values within a generic class?

Why is the compiler giving an error for the following code T' only refers to a type, but is being used as a value here: class Factory<T> { create(TCreator: (new () => T)): T { return new TCreator(); } test(json: string) ...

The error I encountered with the Typescript React <Select> onChange handler type was quite

Having an issue while trying to attach an onChange event handler to a Select component from material-ui: <Select labelId="demo-simple-select-label" id="demo-simple-select" value={values.country} onChange={handleCountryChange} ...

Transitioning from CRA to Gatsby caused issues with JSS plugins

When working with `create-react-app`, I utilized `react-jss` because the `jss-plugin-expand` plugin was not included by default. I had `` set up and everything was functioning properly. However, upon switching to Gatsby, the exact same configuration stoppe ...

What changes can I make to my React components to prevent them from constantly re-rendering?

In my Next.js project, I have a page that displays the content of a transcript and allows users to select portions of the text and make notes on it. The issue I'm facing is outlined below Inside the getServersideProps function, I retrieve a link to ...

I seem to be missing something, as the client_id is required for Next Auth. What could it

I seem to be facing some confusion with where the communication breakdown is occurring. [...nextauth].js import NextAuth from "next-auth" import GoogleProvider from "next-auth/providers/google" export default NextAuth({ provider ...

Module 'csstype' not found

I am diving into the world of React with TypeScript. After setting up react and react-dom, I also installed @types/react and @types/react-dom which all went smoothly. However, a pesky error message keeps popping up: ERROR in [at-loader] ./node_modules/@t ...

Using Typescript to import an npm package that lacks a definition file

I am facing an issue with an npm package (@salesforce/canvas-js-sdk) as it doesn't come with a Typescript definition file. Since I am using React, I have been using the "import from" syntax to bring in dependencies. Visual Studio is not happy about th ...

What causes Next.js code lifecycle to run multiple times?

Recently, I dove into learning Next.js and encountered something peculiar. The issue revolves around this straightforward code snippet: import {useRouter} from 'next/Router'; import {Profile} from '../../components/Profile'; const Jobs ...

The conflict between Material UI's CSSBaseline and react-mentions is causing issues

Wondering why the CSSBaseline of Material UI is causing issues with the background color alignment of React-mentions and seeking a solution (https://www.npmjs.com/package/react-mentions) Check out this setup: https://codesandbox.io/s/frosty-wildflower-21w ...

Add a custom design to the Material UI menu feature

I am currently trying to implement a custom theme using the following code: import Menu from '@material-ui/core/Menu'; import { createStyles, withStyles, Theme } from '@material-ui/core/styles'; const myMenu = withStyles( ( theme: The ...

Effective strategies for extracting value from asynchronous Angular events that return Promises

When it comes to subscription blocks, extracting the value from my API is possible. var data = null; this._timinServiceProxy.getDateFromNTP().subscribe(result => { data = result; console.log(data); // The expected result }); console.log(data); ...

What sets apart TypeScript's indexed types from function signatures?

I am curious about the distinction between indexed type and function signatures in TypeScript. type A = { _(num: number): void; }['_']; type B = { _(ten: 10): void; }['_']; let a: A = (num) => { console.log(num); }; let b: B ...

In React, is it typical to maintain identical values in both state and ref?

When working with my React app, I encountered a situation where I needed to access state values inside setTimeout() and setInterval(). However, due to closures being bound to their context once created, using state values in these functions would not refle ...

Creating Beautiful Tabs with React Material-UI's Styling Features

I've been delving into React for a few hours now, but I'm struggling to achieve the desired outcome. My goal is to make the underline color of the Tabs white: https://i.stack.imgur.com/7m5nq.jpg And also eliminate the onClick ripple effect: ht ...

What is the best way to logout and remove cookies once the jsonwebtoken has expired?

Seeking guidance on clearing a cookie after the 15-second lifetime of a JWT token. Is this task best accomplished on the server side or can it be managed on the client side? Code snippet with description provided below Utilizing mongoose, a user model is ...

`Is There a Solution When Compilation Fails?`

I keep encountering an issue when I run the command npm start. The problem seems to be originating from PancakeSwap Frontend and after several attempts, I am still unable to resolve it. Your assistance is greatly appreciated :) Below is a snippet of my Ap ...

Creating TypeScript domain objects from JSON data received from a server within an Angular app

I am facing a common challenge in Angular / Typescript / JavaScript. I have created a simple class with fields and methods: class Rectangle { width: number; height: number; area(): number { return this.width * this.height; } } Next, I have a ...

Preact: occasional occurrence of a blank page after refreshing

Starting out with Preact & TypeScript, I decided to kickstart my project using the parcel-preact-typescript-boilerplate. Initially, everything seemed to be working smoothly. However, I noticed that occasionally, especially on reload or initial page lo ...

Link the chosen selection from a dropdown menu to a TypeScript object in Angular 2

I have a form that allows users to create Todo's. An ITodo object includes the following properties: export interface ITodo { id: number; title: string; priority: ITodoPriority; } export interface ITodoPriority { id: number; name ...

Steps for generating a unit test for code that invokes scrollIntoView on an HTML element

I'm currently working on an Angular component where I have a method that involves scrolling through a list of elements known as "cards" based on certain criteria. Despite my efforts to write unit tests for this method using the Jasmine framework, I&ap ...