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?
Advertisement
Answer
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.