React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function
Asked Answered
C

36

273

I'm trying to use react hooks for a simple problem

const [personState,setPersonState] = useState({ DefinedObject });

with following dependencies.

"dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-scripts": "3.0.0"
}

but I'm still getting the following error:

./src/App.js

Line 7:
React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks

Line 39:
'state' is not defined
no-undef

Search for the keywords to learn more about each error.

Component code is below:

import React, {useState} from 'react'; 
import './App.css'; 
import Person from './Person/Person'; 

const app = props => { 
    const [personState, setPersonSate] = useState({ person:[ {name:'bishnu',age:'32'}, {name:'rasmi',age:'27'}, {name:'fretbox',age:'4'} ], }); 
    return (
        <div className="App"> 
            <h2>This is react</h2> 
            <Person name={personState.person[1].name} age="27"></Person>
            <Person name={personState.person[2].name} age="4"></Person> 
        </div> ); 
    };
    export default app;

Person component

import React from 'react'; 

const person = props => { 
    return( 
        <div>
            <h3>i am {props.name}</h3>
            <p>i am {props.age} years old</p>
            <p>{props.children}</p>
        </div> 
    )
};

export default person; 
Creatural answered 25/4, 2019 at 10:0 Comment(6)
Can you share your component code?Gasp
import React,{useState} from 'react'; import './App.css'; import Person from './Person/Person'; const app= props => { const [personState,setPersonSate]= useState({ person:[ {name:'bishnu',age:'32'}, {name:'rasmi',age:'27'}, {name:'fretbox',age:'4'} ], }); return ( <div className="App"> <h2>This is react</h2> <Person name={personState.person[1].name} age="27"></Person> <Person name={personState.person[2].name} age="4"></Person> </div> ); };export default app;Creatural
Person Component :- import React from 'react'; const person=(props)=>{ return( <div> <h3>i am {props.name}</h3> <p>i am {props.age} years old</p> <p>{props.children}</p> </div> ) } export default person;Creatural
it's a hell to read such shared code, respect othersGrating
I had the same problem too from Maximilian React course.Concern
The component name & its export name should be App Replace 1. const app --> const App 2. export default app --> export default App;Labyrinth
A
635

Try to capitalize 'app' like

const App = props => {...}

export default App;

In React, components need to be capitalized, and custom hooks need to start with use.

Arabist answered 26/4, 2019 at 7:32 Comment(5)
This is some hard to find bug in an app, I think another comment should be added to the error message to point out this posibility.Government
The reason for this being that in the Rules of Hooks ESLint plugin, there is a check to see if a component or function name is valid: Checks if the node is a React component name. React component names must always start with a non-lowercase letter..Worsley
capitalizing A in App works for me... but not i am thinking why max did not get this error in udemy course ?Stokehole
Same question " why max did not get any error ? I changed " app" to "App" and now it worked for me!Apology
Thanks, The naming was the issue which I was not checking.Wastage
M
87

I feel like we are doing the same course in Udemy.

If so, just capitalize the

const app

To

const App

Do as well as for the

export default app

To

export default App

It works well for me.

Millner answered 8/6, 2019 at 20:51 Comment(3)
Yep I think that makes 3 of us doing the same course. Why is it it's case sensitive?Fleecy
This should be marked as correct answer. By default, "main component" name MUST be capitalized. Also remember to import your components with capitalized names. WRONG: import compo from './Compo'; RIGHT: import Compo from './Compo'; As react recognizes capitalized JSX tags as react components .Guarino
why is it case senstive tho?Emulation
H
58

As far as I know a linter is included into the this package. And it requires you componend should begin from Capital character. Please check it.

However as for me it's sad.

Highly answered 25/4, 2019 at 15:17 Comment(1)
Thanks for saving my time.Cecilla
C
40

Use first letter capital in the function name.

function App(){}
Chickadee answered 26/9, 2019 at 6:50 Comment(2)
"First of all, you need to uppercase the FirstLetter of your components, in your case app should be App and person should be Person." Someone already wrote it...Salina
This has been answered and this should be marked as the answer. Simple solution explained right.Tanto
D
25

React components (both functional as well as class) must begin with a capital letter. Like

const App=(props)=><div>Hey</div>

class App extends React.Component{
   render(){
     return <div>Hey</div>
   }
}

React identifies user-defined components by following this semantic. React's JSX transpiles to React.createElement function which returns an object representation of the dom node. The type property of this object tells whether it is a user-defined component or a dom element like div. Therefore it is important to follow this semantics

Since useState hook can only be used inside the functional component(or a custom hook) this is the reason why you are getting the error because react is not able to identify it as a user-defined component in the first place.

useState can also be used inside the custom hooks which is used for the reusability and the abstraction of logic. So according to the rules of hooks, the name of a custom hook must begin with a "use" prefix and must be in a camelCase

Devitalize answered 7/8, 2020 at 12:39 Comment(2)
Yep worked for me for the react-complete-guide projectArgali
This solved my problem, thanks. The issue was that the function name is starting with small latterHannah
P
20

Use const App instead of const app

Paraphrase answered 9/3, 2020 at 6:45 Comment(0)
J
16

Just try to capitalize your App name

const App = props => {...}

export default App;
Jeb answered 22/1, 2020 at 17:50 Comment(2)
do you mean document title?Tuttifrutti
Its Working, ThanksThigmotaxis
N
13

You are getting this error: "React Hook "useState" is called in function "App" which is neither a React function component or a custom React Hook function"

Solution: You basically need to Capitalize the function.

For example:

const Helper =()=>{}

function Helper2(){}
Newkirk answered 25/7, 2019 at 15:28 Comment(0)
P
12

I had the same issue. turns out that Capitalizing the "A" in "App" was the issue. Also, if you do export: export default App; make sure you export the same name "App" as well.

Precession answered 5/5, 2019 at 12:51 Comment(0)
H
12

the First character of your function should be an Uppercase

Hospitalization answered 24/2, 2020 at 15:15 Comment(1)
Wow, I always forget that. Thanks :)Odoric
D
11

Components should start with capital letters. Also remember to change the first letter in the line to export!

Doublepark answered 7/7, 2019 at 18:16 Comment(1)
Your question doesn't seem like an answer. After reach 50 rep you will be able to comment on questions. If you answer is an answer, try improving it. Why components should start with capital letters, for example? Also, other answers have already said that, are you giving anything new?Scone
C
9

function name must start with a capital letter

For ex:

const App = props => {

}

not const app

Compress answered 29/9, 2021 at 19:13 Comment(0)
K
7

Do you have the right import ?

import React, { useState } from 'react';
Kaon answered 25/4, 2019 at 10:19 Comment(0)
A
6

React components names should be capitalized and custom hooks functions should start with the use keyword to identify as a react hook function.

So, capitalize your app components to App

Almedaalmeeta answered 24/12, 2019 at 6:22 Comment(0)
T
6

your code

import React, {useState} from 'react'; 
import './App.css'; 
import Person from './Person/Person'; 

const app = props => { 
    const [personState, setPersonSate] = useState({ person:[ {name:'bishnu',age:'32'}, {name:'rasmi',age:'27'}, {name:'fretbox',age:'4'} ], }); 
    return (
        <div className="App"> 
            <h2>This is react</h2> 
            <Person name={personState.person[1].name} age="27"></Person>
            <Person name={personState.person[2].name} age="4"></Person> 
        </div> ); 
    };
    export default app;

change it by making the function name capital, like this

import React, {useState} from 'react'; 
import './App.css'; 
import Person from './Person/Person'; 

const App = props => { 
    const [personState, setPersonSate] = useState({ person:[ {name:'bishnu',age:'32'}, {name:'rasmi',age:'27'}, {name:'fretbox',age:'4'} ], }); 
    return (
        <div className="App"> 
            <h2>This is react</h2> 
            <Person name={personState.person[1].name} age="27"></Person>
            <Person name={personState.person[2].name} age="4"></Person> 
        </div> ); 
    };
    export default App;

it will work Thank you.

Transient answered 1/5, 2021 at 2:35 Comment(0)
C
4

I had the same issue, but not with the App. I had a custom class but used a lowercase letter to start the function name and also received the error.

Changed the first letter of the function name and the export line to CamelCase and error gone.

in my case the end result was something like:

function Document() {
....
}
export default Document;

this solved my problem.

Countrybred answered 31/5, 2019 at 14:41 Comment(0)
H
4

In JSX, the lower-case tag name is considered as html native component. In order to react recognise the function as React component, need to Capitalized the name.

Capitalized types indicate that the JSX tag is referring to a React component. These tags get compiled into a direct reference to the named variable, so if you use the JSX <Foo /> expression, Foo must be in scope.

https://reactjs.org/docs/jsx-in-depth.html#html-tags-vs.-react-components

Hew answered 17/1, 2020 at 10:11 Comment(0)
U
3

The solution is simple, correct "app" and write "App" with the first character in uppercase.

Undertaking answered 24/8, 2019 at 21:57 Comment(1)
Welcome to StackOverflow (Upvoted). please put some code and answer to the questions.Salliesallow
A
3

Replace this

export default app;

with this

export default App;
Ashraf answered 12/5, 2020 at 8:51 Comment(0)
U
3

Make function name capital. This works for me.

export default function App() { }
Unfleshly answered 19/6, 2020 at 2:24 Comment(0)
D
3
React Hook "useState" is called in function "App" which is neither a React function component or a custom React Hook function"

For the following error , capitalize the component first letter like, and also the export also.

const App  = props => {
...}
export default App;
Deas answered 3/7, 2020 at 10:36 Comment(0)
W
3

User-Defined Components Must Be Capitalized. In your case you have used const app = props => { }. In "app", 'a' is in lower case, you must try out it to use 'App'

  1. When an element type starts with a lowercase letter, it refers to a built-in component like <div> or <span> and results in a string 'div' or 'span' passed to React.createElement. Types that start with a capital letter like <Foo /> compile to React.createElement(Foo) and correspond to a component defined or imported in your JavaScript file.
  2. React recommend naming components with a capital letter. If you do have a component that starts with a lowercase letter, assign it to a capitalized variable before using it in JSX.

For more details you can check Official Document Click Here

Wastage answered 30/11, 2022 at 5:28 Comment(1)
This is the answerSwinge
U
2

Capitalize the app to App will surely work.

Unsocial answered 9/1, 2020 at 11:58 Comment(0)
N
2

Try to change 'app' name to 'App'

const App = props => {   
  ...
};  
export default App;`
Nummary answered 24/9, 2021 at 14:32 Comment(0)
R
1

The solution, as Yuki already pointed, is to capitalize the component name. It's important to note that not only the "default" App component needs to be capitalized, but all components:

const Person = () => {return ...};

export default Person;

This is due to eslint-plugin-react-hooks package, specifically isComponentName() function inside RulesOfHooks.js script.

Official explanation from Hooks FAQs:

We provide an ESLint plugin that enforces rules of Hooks to avoid bugs. It assumes that any function starting with ”use” and a capital letter right after it is a Hook. We recognize this heuristic isn’t perfect and there may be some false positives, but without an ecosystem-wide convention there is just no way to make Hooks work well — and longer names will discourage people from either adopting Hooks or following the convention.

Ratan answered 31/8, 2019 at 3:16 Comment(0)
T
1

First of all, you need to uppercase the FirstLetter of your components, in your case app should be App and person should be Person.

I tried to copy your code in the hope of finding the issue. Since you did not share how you call the App component, I can only see 1 way to result this to an issue.

This is the link in CodeSandbox: Invalid hook call.

Why? Because of the code below which is wrong:

ReactDOM.render(App(), rootElement);

It should have been:

ReactDOM.render(<App />, rootElement);

For more info, you should read Rule of Hooks - React

Hope this helps!

Trollop answered 31/8, 2019 at 3:45 Comment(0)
A
1

Whenever working with a React functional component, always keep the first letter of the name of the component in Uppercase in order to avoid these React Hooks errors.

In your case, you have named the component app, which should be changed to App, as I said above, to avoid the React Hook error.

Altimeter answered 9/5, 2020 at 1:1 Comment(0)
O
1

Use Capital letter for defining functional component name/ React hooks custom components. "const 'app' should be const 'App'.

App.js

import React, { useState } from 'react';
import { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Person from './Person/Person';

const App = props => {
  const [personState, setPersonState] = useState({
    persons : [
          {name: 'a', age: '1'},
          {name: 'b', age: '2'},
          {name: 'c', age: '3'}
    ]
  });

    return (
      <div>
     <Person name = {personState.persons[0].name} age={personState.persons[0].age}> First </Person>
     <Person name = {personState.persons[1].name} age={personState.persons[1].age}> Second </Person>
     <Person name = {personState.persons[2].name} age={personState.persons[2].age}> Third </Person>    
    );
};
export default App;

Person.js

import React from 'react';

const person = (props) => {
return (
        <div>
<p> My name is {props.name} and my age is {props.age}</p>
<p> My name is {props.name} and my age is {props.age} and {props.children}</p>
<p>{props.children}</p>
        </div>
)
};

[ReactHooks] [useState] [ReactJs]

Oversew answered 8/6, 2020 at 8:39 Comment(0)
P
0

Step-1: Change the file name src/App.js to src/app.js

Step-2: Click on "Yes" for "Update imports for app.js".

Step-3: Restart the server again.

Potash answered 24/12, 2019 at 6:8 Comment(0)
C
0
        import React, { useState } from "react"

    const inputTextValue = ({ initialValue }) => {
        const [value, setValue] = useState(initialValue);
        return {
            value,
            onChange: (e) => { setValue(e.target.value) }
        };
    };

    export default () => {
        const textValue = inputTextValue("");
        return (<>
            <input {...textValue} />
        </>
        );
    }

/*"Solution I Tired Changed Name of Funtion in Captial "*/

    import React, { useState } from "react"

const InputTextValue = ({ initialValue }) => {
    const [value, setValue] = useState(initialValue);
    return {
        value,
        onChange: (e) => { setValue(e.target.value) }
    };
};

export default () => {
    const textValue = InputTextValue("");
    return (<>
        <input {...textValue} />
    </>
    );
}
Cadge answered 13/5, 2020 at 15:36 Comment(0)
L
0

If you are still looking for answer of this question all above stated solution work fine but still i will provide the running/correct code below (edited)

import React, { useState } from 'react';
import './App.css';
import Person from './Person/Person'

  const App = props => {
    const [personsState, setPersonsState ] = useState({
      persons:[
        {name: 'Ram', age: 20},
        {name: 'Rahul', age: 24},
        {name: 'Ramesh', age: 25}
      ],
      otherState: 'Some Other value' 
    });

    const switchNameHandler = () => {
      //console.log('Click is working');
      //Dont Do THIS: this.state.persons[0].name = 'singh';
      setPersonsState({
        persons:[
        {name: 'Ram',age: 20},
        {name: 'Raj', age: 24},
        {name: 'yts', age: 30} 
      ]
    });
    };

    return (
      <div className="App">
        <h1>Nice two one three  Hello i am a noob react developer</h1>
        <button onClick={switchNameHandler}>Switch Name</button>
        <Person name={personsState.persons[0].name} age={personsState.persons[0].age} />
        <Person name={personsState.persons[1].name} age={personsState.persons[1].age}> My hobbies are Gaming</Person>
        <Person name={personsState.persons[2].name} age={personsState.persons[2].age} />
      </div>
    ); 
    // return React.createElement('div',{className:'App'}, React.createElement('h1', null, 'Hi learning the basics of react'));
}

export default App;
Latini answered 4/2, 2021 at 14:48 Comment(1)
Thank you for contributing an answer. Would you kindly edit your answer to to include an explanation of your code? That will help future readers better understand what is going on, and especially those members of the community who are new to the language and struggling to understand the concepts.Dicks
N
0

May be you have added the useEffect that depends on the condition before the one with no condition

EX:

useEffect(() => {
  _anyFunction();
}, []);
    
useEffect(()=> {
  anyCode....
}, [response]);
Neall answered 13/2, 2021 at 12:55 Comment(0)
M
0

I think you take same course that I have because you are using exactly the same variables name in this ,actually you are missing a little thing here that is you change the name of your app with a lower case

export default app

there is a little mistake that is also change the name in index.js you change the name here in the App.js but forgot to change it in index.js you are still importing it like this

import App from './App.js'

so you also had to change the name there

Mile answered 8/3, 2021 at 19:52 Comment(0)
T
0

just as best practice, try to destructure the props element before using it in the Person component. Also use functional components instead of consts. (It is less confusing and you can be done with things faster )

function ({person}) {
  const name={person.name}
  return (
    <h2>{name}</h2>
  )
}
Tolson answered 18/7, 2021 at 10:54 Comment(0)
G
-2

In the app function you have incorrectly spelled the word setpersonSate, missing the letter t, thus it should be setpersonState.

Error:

const app = props => { 
    const [personState, setPersonSate] = useState({....

Solution:

const app = props => { 
        const [personState, setPersonState] = useState({....
Geddes answered 24/5, 2020 at 17:43 Comment(0)
H
-5

Do not use arrow function to create functional components.

Do as one of the examples below:

function MyComponent(props) {
  const [states, setStates] = React.useState({ value: '' });

  return (
    <input
      type="text"
      value={states.value}
      onChange={(event) => setStates({ value: event.target.value })}
    />
  );
}

Or

//IMPORTANT: Repeat the function name

const MyComponent = function MyComponent(props) { 
  const [states, setStates] = React.useState({ value: '' });

  return (
    <input
      type="text"
      value={states.value}
      onChange={(event) => setStates({ value: event.target.value })}
    />
  );
};

If you have problems with "ref" (probably in loops), the solution is to use forwardRef():

// IMPORTANT: Repeat the function name
// Add the "ref" argument to the function, in case you need to use it.

const MyComponent = React.forwardRef( function MyComponent(props, ref) {
  const [states, setStates] = React.useState({ value: '' });

  return (
    <input
      type="text"
      value={states.value}
      onChange={(event) => setStates({ value: event.target.value })}
    />
  );
});
Holdfast answered 29/1, 2020 at 22:58 Comment(2)
Can you explain more, why "Do not use arrow function to create functional components." ? - ThanksPluton
To avoid problems with useState () in some situations, such as in this case: codesandbox.io/s/usestate-error-f452sHoldfast

© 2022 - 2024 — McMap. All rights reserved.