Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript React Components React Component Patterns The React Challenge: Solution

Simon Coates
Simon Coates
8,481 Points

Is there are reason to use useRef for the solution rather than just using a normal javascript variable?

Unless I'm missing something, couldn't you use a normal javascript variable and save yourself a rerender? Something like:

import React, { useState, useRef } from "react";

import Header from './Header';
import Player from "./Player";
import AddPlayerForm from "./AddPlayerForm";

const App = () => {
  const [players, setPlayers] = useState([
    {
      name: "Guil",
      score: 0,
      id: 1
    },
    {
      name: "Treasure",
      score: 0,
      id: 2
    },
    {
      name: "Ashley",
      score: 0,
      id: 3
    },
    {
      name: "James",
      score: 0,
      id: 4
    }
  ]);

  const nextPlayerId = useRef(5);
  const scores = players.map(p => p.score);
  const highScore = Math.max(...scores);

  const handleRemovePlayer = (id) => {
    setPlayers(prevPlayers => prevPlayers.filter(p => p.id !== id));
  }

  const handleScoreChange = (id, delta) => {
    setPlayers(prevPlayers => prevPlayers.map(player => {
      if (player.id === id) {
        return {
          name: player.name,
          score: player.score + delta,
          id: player.id
        }
      }
      return player;
    }));
  }

  const handleAddPlayer = (name) => {
    setPlayers(prevPlayers => [
      ...prevPlayers,
      {
        name,
        score: 0,
        id: nextPlayerId.current++
      }
    ]);
  }

  return (
    <div className="scoreboard">
      <Header
        players={players}
      />

      {/* Players list */}
      {players.map(player =>
        <Player
          name={player.name}
          score={player.score}
          id={player.id}
          key={player.id.toString()}
          removePlayer={handleRemovePlayer}
          changeScore={handleScoreChange}
          isHighScore={player.score === highScore}
        />
      )}
      <AddPlayerForm addPlayer={handleAddPlayer} />
    </div>
  );
}

export default App;

I'm just concerned I'm missing something terribly important. If anyone has any insight, I'd appreciate it.

1 Answer

Clayton Perszyk
MOD
Clayton Perszyk
Treehouse Moderator 48,850 Points

I believe it is because the nextPlayerId is not used in the component's view, so you don't want to cause a re-render of the view and any possible children... If you used a variable and update it, it will cause a re-render...

In short it's used to prevent re-rendering.

Additional details:

  • Only update variables when necessary. Unnecessary re-renders can slow down your application.
  • You can also use the useMemo and useCallback hooks to prevent unnecessary re-renders. (although they're use cases are different than useRef)
Simon Coates
Simon Coates
8,481 Points

Any update to App state that would alter the value of a Player highscore attribute already triggers a rerender. Then 'highScore' variable is only local and shouldn't alter anything in terms of rerenders, I wouldn't have thought. Sorry for not getting back to you at the time. I didn't really understand what you were getting at and just had that general sense that my brain was melting. But I rewatched the series today and wound up writing the same solution (more or less). It's nice to hit a particular wall and then 8 months later find myself beating my head on the same spot.