Skip to content

Instantly share code, notes, and snippets.

@plicjo
Created January 7, 2020 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plicjo/a051f9574b807f49a561b6771e9d9d3e to your computer and use it in GitHub Desktop.
Save plicjo/a051f9574b807f49a561b6771e9d9d3e to your computer and use it in GitHub Desktop.
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