Learn the basics of React Hooks in <10 minutes

An Illustrated Guide on React Hooks.

Ohans Emmanuel
Apr 8, 2019 · 9 min read

Introduction

The Candy Bowl

The State Hook

Class to Hooks — wait for the animation.
function CounterHooks() {

}
function CounterHooks() {

return (
<div>
<h3 className="center">Welcome to the Counter of Life </h3>
<button
className="center-block"
onClick={this.handleClick}> {count} </button>
</div>
);
}
function CounterHooks() {
const handleClick = () => {

}
return (
<div>
<h3 className="center">Welcome to the Counter of Life </h3>
<button
className="center-block"
onClick={handleClick}> {count} </button>
</div>
);
}
//🦄 returns an array with 2 values. 
useState(0)
function CounterHooks() {
// 🦄
const [count, setCount] = useState(0);

const handleClick = () => {
setCount(count + 1)
}

return (
<div>
<h3 className="center">Welcome to the Counter of Life </h3>
<button
className="center-block"
onClick={handleClick}> {count} </button>
</div>
);
}
const [count, setCount] = useState(0);
 
const handleClick = () => {
setCount(count + 1)
}

Multiple useState calls

// single property 
state = {
count: 0
}

// multiple properties
state = {
count: 0,
time: '07:00'
}
useState(0)

const [time, setTime] = useState(new Date())

<p className="center">
at: { `${time.getHours()} : ${time.getMinutes()} : ${time.getSeconds()}`}
</p>

The Effect Hook

useEffect(() => {
// 🐢 you can perform side effects here
console.log("useEffect first timer here.")
})
\
useEffect(() => {
console.log("useEffect first timer here.")
}, [])
useEffect(() => {
console.log("useEffect first timer here.")
}, [count])
count changes when the button is clicked, so the effect function re-runs
useEffect(() => {
const clicked = () => console.log('window clicked');
window.addEventListener('click', clicked);
}, [])
useEffect(() => {
const clicked = () => console.log('window clicked');
window.addEventListener('click', clicked);

return () => {
window.removeEventListener('click', clicked)
}
}, [])

Build Your own Hooks

The Rules of Hooks

Other Candies

We’ve moved to freeCodeCamp.org/news

We’ve moved to https://freecodecamp.org/news and publish tons of tutorials each week. See you there.