Day 003 - Hooks

1 minute read

Hooks?

Today I studied about Hooks.

👉 Day003 github link

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. (from official document)

It provides useState, useEffect which you can perform a variety of tasks that you couldn’t perform in a function component.

📮 You can join newsletter here!

useState

useState is the first Hook that I learned today.

Above output is basic example using useState.

The code looks like below.

import React, { useState } from 'react'

function Index() {
  const [fruit, setFruit] = useState('banana 🍌')

  return (
    <div>
      <p>I like {fruit}</p>
      <button onClick={() => setFruit('peach!! 🍑')}>Change fruit</button>
    </div>
  )
}

useEffect

useEffect is a Hook that you can set to perform certain tasks whenever the React component is rendered.

import React, { useState, useEffect } from 'react'

function Index() {
  const [count, setCount] = useState(0)
  const [fruit, setFruit] = useState('banana 🍌')

  useEffect(() => {
    document.title = `You clicked ${count} times`
    setTimeout(() => {
      console.log(`You clicked ${count} times`)
    }, 3000)
  })

  function handleAlertClick() {
    setTimeout(() => {
      alert('You clicked on: ' + count)
    }, 3000)
  }

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Click me</button>

      <button onClick={handleAlertClick}>Show alert</button>
    </div>
  )
}

I use useEffect to render new title of website.

As you see title change after I clicked button.

useState + useEffect

After making basic examples, I want to use useState and useEffect together.

I make time counter that increased the seconds by the number I inputed.

For example, after I inputed 10 then numbers increase by 10 in a second.

It took more time than I expected to make a example that using useState and useEffect together.

So I’m going to make more examples using Hooks and it could be better if I make real examples.

Official document

A Complete Guide to useEffect by Dan Abramov