skip to Main Content

I just want to know the difference of both options.

Option 1: Outside UseEffect

const [data, setData] = useState(null);
  
  const getData = async () => {
    try {
      const response = await fetch("https://catfact.ninja/fact");
      const result = await response.json();
      setData(result);
    } catch(error) {

    }
  };



  useEffect(() => {
    getData();
  }, [])

  return (
    <>
     <h1>{data?.fact}</h1>
    </>
  )
}

option 2: Inside useEffect

const [data, setData] = useState(null);
  useEffect(() => {
    const getData = async () => {
      try {
        const response = await fetch("https://catfact.ninja/fact");
        const result = await response.json();
        setData(result);
      } catch(error) {
  
      }
    };
  
    getData();
  }, [])

  return (
    <>
     <h1>{data?.fact}</h1>
    </>
  )

I saw that both of them do the same thing but what is the difference and how to perform clean up function for both options and when should I use the option 1 and option 2.

3

Answers


  1. If you function is inside useEffect. You can’t access it from outside. But when your function is outside of useEffect you can call it within your component and inside useEffect also.

    Login or Signup to reply.
  2. Using a function outside the useEffect is more performant. It does not recreated on re-render.

    Login or Signup to reply.
  3. If you consider using variables present in the component, then based on their scopes, your function’s ability to access them will differ.

    Also, the function call inside and outside the useEffect will behave differently.
    In a component,

    • if this function called outside of useEffect, it will execute the
      function on every render of component.
    • if the function call is inside
      the useEffect, you can control when you want to execute the function
      by using dependency array of useEffect hook.

    Regarding clean up function also, if you can access it inside useEffect, there is no difference in its execution. It will execute when the component unmounts.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search