This code seems to work. Nobody does this. What exactly is wrong with it? Under what conditions will it produce bugs?
function App(){
const [b1, n1] = button()
const [b2, n2] = button()
return <div>
<h1>Count 1 is {n1}</h1> {b1}
<h1>Count 2 is {n2}</h1> {b2}
</div>;
}
function button() {
const [n, setN] = React.useState(0)
const b = <button onClick={()=>setN(n=>n 1)}>Increment</button>
return [b, n]
}
It's tidy, so I would like to use it if it's fine.
CodePudding user response:
None. It's totally fine. It has even a name, custom hooks: https://reactjs.org/docs/hooks-custom.html
One of the convention is to give it a name that starts with use
. That also mean that you need to follow all the rules associated with hooks. Documentation here: https://reactjs.org/docs/hooks-intro.html
CodePudding user response:
Instead of using state
directly, why you trying to get it from a function call ? Why can't you create it directly inside your component which is really more readable. And keep this complete part <button onClick={()=>setN(n=>n 1)}>Increment</button>
inside the component instead of the way it's given. It's better to write your code in a more readable manner. Otherwise, it becomes too complicated when it comes to much bigger components.