Sobes.tech
Junior — Senior
31

Оптимизация и улучшение React‑компонента

Условие задачи

Дан React‑компонент Game. Требуется провести рефакторинг, исправив неправильное использование хуков и улучшив читаемость кода.

export const Game = ({ gameId }) => {
  const currentPlatform = useSelector(selectSiteVersion); // 'mobile' | 'desktop'

  const [loading, setLoading] = useState(false);
  const [fullScreen, setFullScreen] = useState(false);
  const [gameInfo, setGameInfo] = useState({ title: '', description: '' });

  if (!gameId) {
    return <div>Empty</div>;
  }

  const requestParams = {
    id: gameId,
    mode: 'real',
    platform: currentPlatform,
  };

  const fetchGame = async () => {
    setLoading(true);
    const game = await requestGame(requestParams);
    setLoading(false);
    setGameInfo(game);
  };

  if (currentPlatform === 'mobile') {
    useEffect(() => {
      fetchGame();
    }, []);
  }

  useEffect(() => {
    const handler = () => setFullScreen(prev => !prev);
    document.addEventListener('fullscreenchange', handler);
    return () => document.removeEventListener('fullscreenchange', handler);
  }, []);

  return (
    <div>
      <div>{gameInfo.title}</div>
      <div>{gameInfo.description}</div>
      {loading && <div>Loading...</div>}
    </div>
  );
};