In this react component how come usestate is working inside a regular function regfunc? It should throw some kind of error but it isn’t.
import { useState } from "react";
export function App() {
let regfunc = () => {
const [color, setColor] = useState("hellojo");
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
2
Answers
Hooks need to be declared at the top-level of a component declaration, but they can also be used inside of other hooks. They always have to be at the top-level inside of a function.
Custom hooks
Here is your component slightly rewritten.
a
outside of theApp
componentuseColor
(hooks should start with "use")The hook returns a string that can be rendered inside of
App
.Function components
The proper way to declare a component in React is to give it a PascalCase name and return some JSX.
The proper way to do this would be to declare the
ColorComponent
outside of the app. You can memoize it to optimize performance and avoid unnecessary re-renders based on prop changes.Or move the component to its own file:
And importing it into your
App.jsx
.Summary
As mentioned by others, as long as you adhere to the rules of Hooks in React, your function will be either treated as a custom hook or a function component.
No, from the rules-of-hooks:
So it’s better to make the
Color
a custom component like so: