0

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

"You can definitely avoid this by using if-statements inside the function". I agree that the question needs more details, but in general this is an anti-pattern
You call this function that has setState as an argument a hook? Really? This function as said by OP is used to update component state.. and yes it is an anti-pattern to pass setState to functions outside of React's scope
(I don't get notification you replied if you don't @ ping me.) I somehow managed to miss the part of the question where they said it set state. o_O My bad!! :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.