2

I would like to create a bunch of filters to pause or play my Video. My implementation is something like as shown below:

const Player = () => {
  const playFilters = [useIsPageVisible(), useIsInViewport(videoElement)];
  const player = useInitPlayer();

  useEffect(() => {
    if (player) {
      if (playFilters.every((filter) => filter)) {
        player.play()
      } else {
        player.pause()
      }
    }
  }, [player, playFilters])

return <Player player={player}/>
}

I know defining hooks inside an if condition is not correct. But how about defining them as above? Could it be done in a better way?

2
  • 3
    It's fine, it didn't violate any rule Commented Aug 9, 2022 at 8:27
  • Related: Array of hooks in React Commented Jul 5, 2024 at 23:48

1 Answer 1

4

In order for React to correctly preserve the state of Hooks, it's crucial that hooks are called in the same order each time a component renders. That's why one of the Rules of Hooks is Don’t call Hooks inside loops, conditions, or nested functions.

Storing hook results in an array does not break that rule (or any other rule), there it is is perfectly fine to do that.

See more details here.

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

Comments

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.