Understanding react hooks

Understanding react hooks

Vol 1. useState

Introduction

useState is one of the React hooks. And its use can not be over-emphasized. It comes in handy when building a React app.

In React there is what we call the state of an application. This is quite different from when dealing with vanilla JavaScript (in which you would need to manually grab HTML elements to change the values or update them in the webpage.

How it works

Using useState helps us grab everything about the element. It grabs the UI, the logic, and the variable - everything! Once the state of the application changes, the web will automatically re-render the elements connected to the state.

Examples

Won't work

The increment button is actually increasing the counter but not reflecting in the webpage because there is not a re-rendering. And this is where useState comes in handy. Check the console for the code below

NB: The increment button is actually increasing the counter but it is not reflected in the webpage because React is not aware of the changes. This is where useState comes in handy. Check the console for the code below.

What works

Ex 1:

NB: In the code above, React is aware that the initial state of the counter is 0. And when the increment button is clicked, it updates the element connected to the state after re-rendering. Check the image below.

NB: The button can now increase the counter when clicked.

Ex 2:

In this example, one of the common ways of using useState would be used to demonstrate it. And that is the use of input.

import React, {useState} from 'react'
import './UseState.css'
const UseState = () => {

    // let counter = 0
    // const handleIncrement = () => {
    //     counter = counter + 1
    //     console.log(counter)
    // }

    // // NB: This is actually working. Clicking the increment button increases the counter but react is not asked to re-render. Check the console.

    // const [counter, setCounter] = useState(0)

    // const handleIncrement = () => {
    //     setCounter(prevState => prevState + 1)
    // }

    const [input, setInput] = useState('') // NB: This means an empty string is the initial state
    return (
    <div className='useStateWrapper'>
       <div className='useStateContent'>
        <h1>useState</h1>
        <h2>{input}</h2>
        <input type='text' onChange={e => setInput(e.target.value)} placeholder="Type something" className='useStateInput'/>
       </div>
    </div>
  )
}
export default UseState

NB: Once you start typing, the empty string would be updated and changed to whatever you have typed. This is because React is keeping track of all changes that happen and update the former state with the current state. This is possible because React knows about the former state. And that is the power of useState hook! Check the result below.

NB: The initial state which is an empty string has been updated to 'Jesus is Lord'.

Ex 3:

Another important aspect of useState that I would like to talk about is flipping between states. For example, how can you change from a state of false to true by clicking a single button? I am going to use a background color to explain this. And the summary is, if the color is true, let the background color of an element be red and if false, let it be blue.

import React, {useState} from 'react'
import './UseState.css'
const UseState = () => {

    // let counter = 0
    // const handleIncrement = () => {
    //     counter = counter + 1
    //     console.log(counter)
    // }

    // // NB: This is actually working. Clicking the increment button increases the counter but react is not asked to re-render. Check the console.

    // const [counter, setCounter] = useState(0)

    // const handleIncrement = () => {
    //     setCounter(prevState => prevState + 1)
    // // }

    // const [input, setInput] = useState('') // NB: This means an empty string is the initial state

    const [color, setColor] = useState(false)

    const handleColorChange = () => {
        setColor(prevState => !prevState)
    }
    return (
    <div className='useStateWrapper'>
       <div className='useStateContent'>
        <h1>useState</h1>
        <h2 style={{ backgroundColor: color ? 'red' : 'blue' }}>
            {
                color ? <h3>My background color is red</h3> : <h3>My background color is blue</h3>
            }
        </h2>
        <button onClick={handleColorChange} className="useStateColor-btn">Change Color</button>
       </div>
    </div>
  )
}
export default UseState

NB: The background color of the h2 element and the inner text of the h3 element are changed or updated based on the condition of whether the state is true or false. Check the results below.

Conclusion

In conclusion, I believe that this writing of mine must have made the React useState hook very clear to you. Look forward to more from me. Thanks for taking the time to read it.