Currying can save passing extra props!

saksham-malhotra

Saksham Malhotra

Posted on January 9, 2024

Currying can save passing extra props!

Before we proceed with using currying in a sample React example to omit passing extra props, do check out what currying is.

Let's consider a simple example where we are developing the players section in a game and the player names are editable

const Players = () => {
    const [playerNames, setPlayerNames] = useState(["Player 1", "Player 2"]);

    function updatePlayerName(index, name) {
        setPlayerNames((prevPlayers) => {
            prevPlayers[index] = name;
            return [ ...prevPlayers ];
        });
    }

    return (
        <>
            {playerNames.map((playerName, index) => {
                <Player
                    key={index}
                    name={playerName}
                    index={index}
                    updatePlayer={updatePlayerName}
                ></Player>;
            })}
        </>
    );
}
Enter fullscreen mode Exit fullscreen mode

Note that we are passing a prop called index just to enable updating name at a particular index in the state. But apart from that, there should be no use of index in the child Player component.

How can we avoid passing this extra index prop?

You guessed it right, by using the concept of currying. We can simply curry the setPlayerName method as

function updatePlayerName(index) {
    return function (name: string) {
        setPlayerNames((prevPlayers) => {
            const updatedPlayers = [...prevPlayers];
            updatedPlayers[index] = name;
            return updatedPlayers;
        });
    };
}
Enter fullscreen mode Exit fullscreen mode

and call it in the template as

updatePlayer={updatePlayerName(index)}
Enter fullscreen mode Exit fullscreen mode

Note that now the updatePlayerName function is invoked inline in the template instead of being just assigned as a reference. This helps return a new curried reference to the function to pass down thus eliminating the need of passing index as an additional prop.

Best of coding!

πŸ’– πŸ’ͺ πŸ™… 🚩
saksham-malhotra
Saksham Malhotra

Posted on January 9, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related