2019-04-10
I learned a lot about React after I followed the tutorial provided by reactjs.org, which is building a tic-tac-toe game. In my opinion, the tutorial is quite challenging, it consists of several stages with increasing difficulty from creating the game's logic to adding a history and time travel features.
After I have completed the tutorial, I felt excited and had the urge to challenge myself to build the game again but this time with the new hype: React Hooks
The challenge with hooks was figuring out how to change the class components into functional components, which was not possible before hooks came out.
The first thing that I did was desctructuring some props from Square component and changed the Board class component into a functional component. Here is the change that I did for Square component:
function Square({ value, onClick }) {
return (
<button className='square' onClick={onClick}>
{value}
</button>
);
}
It looks cleaner with the props destructured. The next code changed was the Board component:
function Board({ squares, onClick }) {
function renderSquare(i) {
return <Square value={squares[i]} onClick={() => onClick(i)} />;
}
}
Next, I went with Game component, for the state, I replaced it with useState
such as the code below:
import React, { useState } from 'react';
...
...
const [history, setHistory] = useState([{ squares: Array(9).fille(null )}])
const [stepNumber, setStepNumber] = useState(0);
const [XisNext, setNext] = useState(true);
handleClick(i) {
const newHistory = history.slice(0,stepNumber + 1);
...
...
squares[i] = XisNext ? 'X' : 'O';
setHistory(newHistory.concat([{ squares }]));
setStepNumber(newHistory.length);
setNext(!XisNext);
...
}
Wow, look at the code above, it looks cleaner and more readable compared to using class and state. By the way, you can look the original code (without hooks) from this codepen.
Overall, the main purpose of using React Hooks is to make React back to functional programming. React is a JavaScript library, while JavaScript itself is a functional programming. Using hooks can avoid the use of this and bind keywords and provides simplicity.