One of the lessons from The Joy of React course is to build a Wordle clone to practice state management. It’s a challenging project for someone who has never tried to make any projects from scratch.
State management has always been a hurdle for anyone who wants to learn to program because it can be highly confusing. However, especially in React, where the focus is more on building a web app, how you manage states will dictate the complexity of your components.
During the practice, I discovered I’ve passed too many states into the child components. For example, during the first part of the project, you create a Game
component that renders a Banner
component with a button that allows you to reset the game.
Here are the states I pass into the Banner
component.
<Banner
gameResult={gameResult}
setGameResult={setGameResult}
guessCount={guessCount}
gameAnswer={gameAnswer}
setGameAnswer={setGameAnswer}
setGuessHistory={setGuessHistory}
setIsDisabled={setIsDisabled}
setGuessCount={setGuessCount}
/>
I learned I needed those states because I tucked the game logic inside the Banner
component. You can keep the code straightforward by passing the function that handles the game logic into the Banner
component.
function resetGame() {
const nextGuessHistory = [];
setGuessHistory(nextGuessHistory);
const nextGameResult = 'Ongoing';
setGameResult(nextGameResult);
const nextGameAnswer = sample(WORDS);
setGameAnswer(nextGameAnswer);
setGuessCount(0);
setIsDisabled(false);
}
// Rest of the code
<Banner
gameResult={gameResult}
setGameResult={setGameResult}
guessCount={guessCount}
gameAnswer={gameAnswer}
resetGame={resetGame}
/>
I sensed that some of the components I created were too complicated for this project. So here are some signs that you’re also making the component complicated.
- Passing too many
setState
functions into the child components. - Put the logic that handles the parent states as part of the descendant components.
I’ve changed my approach whenever I need to create a new component. I will only pass state value for the child components to render at first. Then, if I need the child components to update the result of the parent states, I can pass a function that wrangles all the setState
functions together.
The exercise is refreshing because I haven’t attempted to build projects beyond writing HTML and CSS for static sites. Although I had experience putting things together in Jekyll, this is the second time I’m learning something by following a course.