Examples of a few hooks.
npm installnpm start
| import React, {useState, useEffect, useMemo, useRef} from 'react'; | |
| import {render} from 'react-dom'; | |
| const emoji = ['😠', '😡', '🤬', '😡'] | |
| function Disappearer(){ | |
| const [currentEmojiIndex, setCurrentEmoji] = useState(0); | |
| useEffect(() => { | |
| console.log('On Disappearer Mount'); | |
| const intervalID = setInterval(() => { | |
| setCurrentEmoji(i => (i + 1) % 4); | |
| }, 500); | |
| // This is cleanup like componentDidUnmount | |
| return () => { | |
| console.log('On Disappearer Unmount') | |
| clearInterval(intervalID); | |
| } | |
| }, []); | |
| return <span>{emoji[currentEmojiIndex]}</span> | |
| } | |
| function KitchenSink(){ | |
| const [count, setCount] = useState(0) | |
| useEffect(() => { | |
| console.log("Effect 1 Happened"); | |
| }, [/* Empty Array Means Only Do This At The Beginning */]); | |
| const tens = useMemo(() => { | |
| console.log('Tens Calculated'); | |
| return Math.floor(count / 10); | |
| }, [Math.floor(count / 10)]) | |
| return <div> | |
| <h1>Kitchen Sink</h1> | |
| <div> | |
| <h2>Use State</h2> | |
| <p> | |
| <button onClick={() => setCount(c => c + 1)}>Click</button> | |
| {count} Clicks {tens} {count % 10 === 0 && <Disappearer/>} | |
| </p> | |
| </div> | |
| </div> | |
| } | |
| render(<KitchenSink/>, document.getElementById('react-root')); |
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
| <title>Kitchen Sink</title> | |
| <link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet"> | |
| <style> | |
| * { | |
| font-family: 'Raleway', sans-serif; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div id="react-root"></div> | |
| <script src="./app.jsx"></script> | |
| </body> | |
| </html> |
| { | |
| "name": "kitchen-sink", | |
| "version": "1.0.0", | |
| "description": "", | |
| "main": "index.js", | |
| "scripts": { | |
| "start": "parcel index.html app.jsx" | |
| }, | |
| "keywords": [], | |
| "author": "Joel Shinness <me@joelshinness.com> (http://joelshinness.com)", | |
| "license": "ISC", | |
| "dependencies": { | |
| "parcel-bundler": "^1.12.3", | |
| "react": "^16.8.6", | |
| "react-dom": "^16.8.6" | |
| } | |
| } |