Created
January 7, 2020 15:46
-
-
Save plicjo/a051f9574b807f49a561b6771e9d9d3e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from 'react'; | |
export default function HookExample() { | |
// State hook | |
const [count, setCount] = useState(0) | |
// Using multiple state hooks | |
// const [age, setAge] = useState(42); | |
// const [fruit, setFruit] = useState('banana'); | |
// const [todo, setTodo] = useState(null)' | |
// | |
// Effect Hook | |
useEffect(() => { | |
document.title = `You clicked ${count} times!` | |
}) | |
// Multiple Effect Hooks | |
useEffect(() => { | |
localStorage.setItem('count', count) | |
// Cleaning up effects, aka componentWillUnmount | |
return () => { | |
console.log('Cleanup!') | |
localStorage.setItem('count', null) | |
} | |
}) | |
// 2 Rules of Hooks | |
// 1. Hooks must be called at the top level of the component | |
// 2. Hooks must be called within a React Function | |
return( | |
<div> | |
<p className="text-info"> | |
You clicked {count} times! | |
</p> | |
<button className='btn btn-primary' onClick={ () => setCount(count + 1) }> | |
Click me! | |
</button> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment