Reputation: 13
I'm trying to call a function in useEffect()
by doing this:
const myComponent = () => {
useEffect(() => {
const aFunc = () => {
console.log("function called")
}
}, [])
return (
<button onClick={() => aFunc()} />
)
}
As you can see, everytime I click on the <button>
I would like to call the aFunc()
function.
How can I call the aFunc
outside of useEffect()
but in the same component? It seems that React can't recognize the function when I bind it in the onClick
Upvotes: 1
Views: 5383
Reputation: 164
Adding on to Dostonbek Oripjonov's answer
Just declare the function outside the useEffect hook and then call it from inside the hook.
This would allow you to use that function in other places too!
Upvotes: 0
Reputation: 1674
I think you want this
const myComponent = () => {
const aFunc = () => {
console.log("function called")
}
useEffect(() => {
aFunc()
}, [])
return (
<button onClick={() => aFunc()} />
)
}
Upvotes: -1
Reputation: 54
You dont need to use useEffect for this,
const myComponent = () => {
const aFunc = () => {
console.log("function called")
}
return (
<button onClick={() => aFunc()} />
)
}
Upvotes: 0
Reputation: 943207
You can't. The function exists in a different scope.
The point of useEffect
is to isolate code so it doesn't rerun every time a component renders. The most common use for this is to make an Ajax request for data when the component is added to the document without triggering an infinite loop as every Ajax response causes the component to rerender and trigger the Ajax request to be made again.
Just declare the function directly inside the component or, since the function in this particular example doesn't depend on any data from the component, entirely outside the component.
If your example is massively over simplified and the process of creating the function is expensive and dependent on data in the component: Look at useCallback
.
Upvotes: 3