Search code examples
javascriptreactjsreact-hooksfrontend

Why Doesn't useState Work in My React Component, and How Can I Fix It?


I'm having an issue with useState in one of my React components. Although I've used useState successfully in another component, it doesn't seem to work in this one, and I'm getting the following error:

Line 7:31: React Hook "useState" is called in function "categories" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use".

Here’s the code for the component where I’m encountering the issue:

import React, { useState } from 'react';
import { useDropzone } from 'react-dropzone';
import styles from './categories.module.css';
const categories = () => {
   const [isOpen, setOpen] = useState(false);

  return (
      <div>
          <button className={`styles.menu ${isOpen ? "active" : ""}`} onClick={() => setOpen(!isOpen)}>
              <div className="div">TRP</div>
          </button>
          <nav className={styles.menu}>
              <ul className={styles.menu__list}>
                  <li className={styles.menu__item}>TRP</li>
                  <li className={styles.menu__item}>Investments</li>
              </ul>
          </nav>
      </div>
  );

};

What I've Noticed:

Error Explanation: The error message indicates that useState is being called in a function that is neither a React component nor a custom Hook, and it also mentions that component names must start with an uppercase letter.
Working Example: I have another component where I used useState in a similar way, and it works perfectly fine.

My Questions:

Why is useState not working in this component?
What exactly does the error message mean when it refers to the component name needing to start with an uppercase letter?
How can I fix this issue so that useState works correctly in this component?

Any guidance on what I’m doing wrong and how to resolve this would be greatly appreciated!

export default categories;


Solution

  • I tested your code on my own machine and it works fine for me,but based on what you've sent I think the problem might be from the fact that you didn't start your component's name with uppercase letter.

    and by the way I think you should replace this with your current button tag:

    <button className={`${styles.menu}${isOpen ? "active" : ""}`} onClick={() => setOpen (!isOpen)}>