Introduction to React Hooks

Learn how Hooks can help you build a React application

Access state

import { useState } from 'react'const Counter = () => {
const [count, setCount] = useState(0)
return (
<div>
<p>You clicked {count} times</p>
<button onClick​={() => setCount(count + 1)}>Click me</button>
</div>
)
}
ReactDOM.render(<Counter />, document.getElementById('app'))

Access lifecycle hooks

const { useEffect, useState } = Reactconst CounterWithNameAndSideEffect = () => {
const [count, setCount] = useState(0)
const [name, setName] = useState('Flavio')
useEffect(() => {
console.log(`Hi ${name} you clicked ${count} times`)
})
return (
<div>
<p>
Hi {name} you clicked {count} times
</p>
<button onClick​={() => setCount(count + 1)}>Click me</button>
<button onClick​={() => setName(name === 'Flavio' ? 'Roger' : 'Flavio')}>
Change name
</button>
</div>
)
}
ReactDOM.render(
<CounterWithNameAndSideEffect />,
document.getElementById('app')
)
useEffect(() => {
console.log(`Hi ${name} you clicked ${count} times`)
return () => {
console.log(`Unmounted`)
}
})
useEffect(
() => {
console.log(`Hi ${name} you clicked ${count} times`)
},
[name, count]
)
useEffect(() => {
console.log(`Component mounted`)
}, [])

Enable cross-component communication using custom hooks

const useGetData() {
//...
return data
}
const useGetUser(username) {
//...const user = fetch(...)
//...const userData = ...
return [user, userData]
}
const MyComponent = () => {
const data = useGetData()
const [user, userData] = useGetUser('flavio')
//...
}

I create easy to digest Front-end related articles here.Yo'll find me writing about everything from JavaScript basics,to larger framework and library tutorials.