Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the better way to run function only for once, useEffect or just call the function in Hooks? [closed]

We can use useEffect to call function for once if we pass empty array as a dependency, but also can just call functions without the hook, just call it.

I tried to search what's the better way to call function only for first render, but I could only find posts recommend to use useEffect with empty array. But why? Does it more conventional?

What's the better way and why is that?

  • Edit) I think I made some wrong question. Sorry about it for the first. My question is more like this.

We can call function in body so that can be used to every render. I know if we don't suggest second parameter, dependencies, then it will call render on every works. But what's the benefit from using 'useEffect'? We can make a same goal with both - calling in the useEffect and body.

like image 640
lcpnine Avatar asked Oct 29 '25 08:10

lcpnine


1 Answers

I would suggest reading about react's life cycle here. This is a basic concept and must be mastered.

Calling a function straight in the body can help with debugging (such as using console logs) but is not a good practice and will consume a lot of memory. If this function sets the state, it will create an infinite loop and break your code.

By rule of thumb, never call functions in the body of your component.

Any side effects should either run by user input (pressing a button, typing, etc..) or by useEffect when a state changes.

Take a look at this example:

const example = () => {
    const [counter, setCounter] = useState(0);
    const [text, setText] = useState('');

    // Calling a function in the body runs it on every render
    // And is considered a bad practice, as any state change
    // Will cause it to run and consume memory
    myfunction();
     
    const myFunction =() => { console.log('this will run on every render')}

    useEffect(() => {
      //This useEffect acts as componentDidMount
      //It will only run once when the component mounts, since 
      // the dependency array is empty
      console.log('mount');
    }, []);


   useEffect(() => {
      // This will run once on mount and every time
      // count changes. Typical use of useEffect
      // This won't run when text changes.
      console.log('count up', count);
    }, [count]);


   return (
   <>
    <button onClick={() => setCounter(counter + 1)} >
     Clicked {counter} times
    </button>
    <input 
       placeholder="Any text here" 
       value ={text} 
       onChange={(e) => {setText(e.target.value)}}
/>
   </>
   )

}
like image 126
Thales Kenne Avatar answered Oct 30 '25 23:10

Thales Kenne