Mrmld Sky
Mrmld Sky

Reputation: 149

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>)
}

Upvotes: 0

Views: 1819

Answers (1)

Tasos
Tasos

Reputation: 2036

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

Upvotes: 2

Related Questions