How to call a function in useEffect() outside of it

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


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.

Leave a Reply

Your email address will not be published. Required fields are marked *