Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling function directly in functional component body in React.js

I have a functional component and some function is called directly in the body (that function changes the state && it’s needed to be run each render). Is it 100% okay, or could it cause bugs?

const myFunc = (setMyState, ...) => {
    ...
    setMyState(...)
}

const MyComponent = () => {
    const [myState, setMyState] = useState(...)
    myFunc(setMyState, ...)
    return(<div>some content...</div>)
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This will cause an infinite loop. This is why:

  1. component renders first time
  2. function updates component state
  3. component renders because of state update
  4. function runs again and updates component again
  5. etc

You can definitely avoid this by using if-statements inside the function, but the best way to update a component state is either by user input/api calls or props updating(your case I suppose)

The best way to do that in my opinion is using the useEffect hook

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading