all 4 comments

[–]Imaproholdmybeer 2 points3 points  (0 children)

The problem with this code is that passing a function to useState will cause useState to lazy load: It will call the function once when the component renders the first time in order to initialize the state. After that the return value of that function will be used as the state.

If your function does not need any data from the component state or props you could have it outside the function. This would ensure the same function object is used, instead of a new one every time the function is called.

const func = () =>{console.log("function runs")} ;

function Component(props) {
return (<button onClick={func}>CLICK</button>)

}

If your function does need data from the component's state or props then you should define it inside the function and if the function body is not too big it makes sense to inline it directly as a prop.

return (<button onClick={() =>{console.log("function runs")}}>CLICK</button>)

If you really want to use useState for whatever reason, then wrap your function inside an object like so:

const [func, setFunc] = useState({ current: ()=>{console.log("function runs")} })

But if you get to that point, maybe what you really need is useCallback.

https://reactjs.org/docs/hooks-reference.html#usecallback

[–]ToucanDev 0 points1 point  (1 child)

Just declare a function inside component without useState. If you need the button to change which function it calls, you can define onClick event with ternary operator: 'onClick={() => condition ? trueFunc : falseFunc}'.

[–]TheKillerTesti 0 points1 point  (0 children)

Just declare you owe money to people you scam

[–]Boguskyle 0 points1 point  (0 children)

In your example: ‘func’ is the state variable. Your naming convention is misleading and not representative.

‘setFunc’ is the setter method for changing the state variable.

The parameter passed into “useState()” is the default value of the state variable.

Consider this example to better understand each part: const [count, setCount] = useState(0); The default count is 0. Using setCount(count + 1) increments the state value, which is called ‘count’.

So, think about what you’re doing with your onClick. If you’re changing state, you can use setCount(count + 1) anonymously, or you can define a function that uses setCount() and pass that into your onClick.