# Hooks Project

## Speed Typing Game with Hooks

{% tabs %}
{% tab title="App.js" %}

```jsx
import React, {useState, useEffect, useRef} from "react"

function App() {
    // Set states
    const [text, setText] = useState("")
    const [timeRemaining, setTimeRemaining] = useState(5)
    const [isTimeRunning, setIsTimeRunning] = useState(false)
    const [wordCount, setWordCount] = useState(0)
    const textAreaInput = useRef(null)
    
    // Handle textarea input
    function handleChange(event){
        const {value} = event.target
        setText(value)
    }
    
    // Calculate total no. of words in the textarea
    function calcNoOfWords(text){
        // trim whitspace and turn the string into array
        const wordArr = text.trim().split(" ")
        // don't count empty string as word
        const filteredArr = wordArr.filter(word => word !== "")
        // measure array length
        const totalWords = filteredArr.length
        return totalWords
    }
    
    // Handle Start of the Game
    function startGame(){
        // Start game timer
        setIsTimeRunning(true)
        // Game duration is 5 second
        setTimeRemaining(5)
        // Make textarea blank after the time is ended (reaches to 0 second)
        setText("")
        // Enable textarea when the startGame() function runs
        textAreaInput.current.disabled = false
        // Auto foucs textarea
        textAreaInput.current.focus()
    }
    
    // Handle End of the Game
    function endGame(){
        // Stop game timer
        setIsTimeRunning(false)
        // Calculate the total no. of words after the game ends
        setWordCount(calcNoOfWords(text))
    }
    
    // Handle effect
    useEffect(() => {
        if(isTimeRunning && timeRemaining > 0){
            setTimeout(()=>{
                setTimeRemaining(time => time - 1) // Timer decreases by 1 second 
            }, 1000)
        } else if(timeRemaining===0){
            endGame() // End the game if timer reaches to 0
        }
    },[timeRemaining, isTimeRunning]) // useeffect runs each time `timeRemaining` and `isTimeRunning` updates
    
   
    return(
        <div>
            <h1>Speed Typing Game</h1> 
            <textarea
            ref={textAreaInput}
            value={text}
            onChange={handleChange}
            disabled={!isTimeRunning} // disable textarea until the Timer hasn't started
             /> 
            <h4>Time Remaining: {timeRemaining}</h4>
            <button 
            onClick={startGame}
            disabled={isTimeRunning} // disable button after the Timer has started
            >
            Start</button>
            
            <h1>Word Count: {wordCount}</h1>
        </div>
    )    
}

export default App

```

{% endtab %}

{% tab title="index.js" %}

```jsx
import React from "react"
import ReactDOM from "react-dom"
import App from "./App"

ReactDOM.render(<App />, document.getElementById("root"))

```

{% endtab %}
{% endtabs %}
