├── public ├── favicon.ico ├── manifest.json └── index.html ├── src ├── levels │ ├── Level01.js │ ├── Level03.js │ ├── Level02.js │ ├── Level00.js │ ├── Level04.js │ ├── Level06.js │ ├── Level05.js │ ├── Level07.js │ ├── Level08.js │ ├── Level09.js │ ├── Level10.js │ ├── Level11.js │ └── Level12.js ├── index.js ├── App.js └── serviceWorker.js ├── .gitignore ├── package.json └── README.md /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sdolidze/react-hooks-interval/HEAD/public/favicon.ico -------------------------------------------------------------------------------- /src/levels/Level01.js: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react'; 2 | 3 | // setInterval 4 | export default function Level01() { 5 | console.log('renderLevel01'); 6 | 7 | const [count, setCount] = useState(0); 8 | 9 | setInterval(() => { 10 | setCount(count + 1); 11 | }, 500); 12 | 13 | return
count => {count}
; 14 | } 15 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": ".", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /src/levels/Level03.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | 3 | // run only once 4 | export default function Level03() { 5 | console.log('renderLevel03'); 6 | 7 | const [count, setCount] = useState(0); 8 | 9 | useEffect(() => { 10 | setInterval(() => { 11 | setCount(count + 1); 12 | }, 300); 13 | }, []); 14 | 15 | return
count => {count}
; 16 | } 17 | -------------------------------------------------------------------------------- /src/levels/Level02.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | 3 | // useEffect 4 | export default function Level02() { 5 | console.log('renderLevel02'); 6 | 7 | const [count, setCount] = useState(0); 8 | 9 | useEffect(() => { 10 | setInterval(() => { 11 | setCount(count + 1); 12 | }, 500); 13 | }); 14 | 15 | return
Level 2: count => {count}
; 16 | } 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /src/levels/Level00.js: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react'; 2 | 3 | // hello world 4 | export default function Level00() { 5 | console.log('renderLevel00'); 6 | 7 | const [count, setCount] = useState(0); 8 | 9 | return ( 10 |
11 | count => {count} 12 | 13 | 14 |
15 | ); 16 | } 17 | -------------------------------------------------------------------------------- /src/levels/Level04.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | 3 | // cleanup 4 | export default function Level04() { 5 | console.log('renderLevel04'); 6 | 7 | const [count, setCount] = useState(0); 8 | 9 | useEffect(() => { 10 | const interval = setInterval(() => { 11 | setCount(count + 1); 12 | }, 300); 13 | return () => clearInterval(interval); 14 | }, []); 15 | 16 | return
count => {count}
; 17 | } 18 | -------------------------------------------------------------------------------- /src/levels/Level06.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | 3 | // setTimeout 4 | export default function Level06() { 5 | console.log('renderLevel06'); 6 | 7 | const [count, setCount] = useState(0); 8 | 9 | useEffect(() => { 10 | const timeout = setTimeout(() => { 11 | setCount(count + 1); 12 | }, 300); 13 | return () => clearTimeout(timeout); 14 | }, [count]); 15 | 16 | return
count => {count}
; 17 | } 18 | -------------------------------------------------------------------------------- /src/levels/Level05.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | 3 | // use count as deps 4 | export default function Level05() { 5 | console.log('renderLevel05'); 6 | 7 | const [count, setCount] = useState(0); 8 | 9 | useEffect(() => { 10 | const interval = setInterval(() => { 11 | setCount(count + 1); 12 | }, 300); 13 | return () => clearInterval(interval); 14 | }, [count]); 15 | 16 | return
count => {count}
; 17 | } 18 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /src/levels/Level07.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | 3 | // functional updates for useState 4 | export default function Level07() { 5 | console.log('renderLevel07'); 6 | 7 | const [count, setCount] = useState(0); 8 | 9 | useEffect(() => { 10 | console.log('useEffect'); 11 | const interval = setInterval(() => { 12 | console.log('setInterval'); 13 | setCount(c => c + 1); 14 | }, 300); 15 | return () => clearInterval(interval); 16 | }, []); 17 | 18 | return
count => {count}
; 19 | } 20 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-hooks-interval", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "react": "^16.8.4", 7 | "react-dom": "^16.8.4", 8 | "react-scripts": "2.1.8" 9 | }, 10 | "scripts": { 11 | "start": "react-scripts start", 12 | "build": "react-scripts build", 13 | "test": "react-scripts test", 14 | "eject": "react-scripts eject" 15 | }, 16 | "eslintConfig": { 17 | "extends": "react-app" 18 | }, 19 | "browserslist": [ 20 | ">0.2%", 21 | "not dead", 22 | "not ie <= 11", 23 | "not op_mini all" 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /src/levels/Level08.js: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react'; 2 | 3 | // local variable 4 | export default function Level08() { 5 | console.log('renderLevel08'); 6 | 7 | const [count, setCount] = useState(0); 8 | 9 | let interval = null; 10 | 11 | const start = () => { 12 | interval = setInterval(() => { 13 | setCount(c => c + 1); 14 | }, 500); 15 | }; 16 | 17 | const stop = () => { 18 | clearInterval(interval); 19 | }; 20 | 21 | return ( 22 |
23 | count => {count} 24 | 25 | 26 |
27 | ); 28 | } 29 | -------------------------------------------------------------------------------- /src/levels/Level09.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useRef } from 'react'; 2 | 3 | // useRef 4 | export default function Level09() { 5 | console.log('renderLevel09'); 6 | 7 | const [count, setCount] = useState(0); 8 | 9 | const intervalRef = useRef(null); 10 | 11 | const start = () => { 12 | intervalRef.current = setInterval(() => { 13 | setCount(c => c + 1); 14 | }, 500); 15 | }; 16 | 17 | const stop = () => { 18 | clearInterval(intervalRef.current); 19 | }; 20 | 21 | return ( 22 |
23 | count => {count} 24 | 25 | 26 |
27 | ); 28 | } 29 | -------------------------------------------------------------------------------- /src/levels/Level10.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useRef } from 'react'; 2 | 3 | // handle multiple calls 4 | export default function Level10() { 5 | console.log('renderLevel10'); 6 | 7 | const [count, setCount] = useState(0); 8 | 9 | const intervalRef = useRef(null); 10 | 11 | const start = () => { 12 | if (intervalRef.current !== null) { 13 | return; 14 | } 15 | 16 | intervalRef.current = setInterval(() => { 17 | setCount(c => c + 1); 18 | }, 500); 19 | }; 20 | 21 | const stop = () => { 22 | if (intervalRef.current === null) { 23 | return; 24 | } 25 | 26 | clearInterval(intervalRef.current); 27 | intervalRef.current = null; 28 | }; 29 | 30 | return ( 31 |
32 | count => {count} 33 | 34 | 35 |
36 | ); 37 | } 38 | -------------------------------------------------------------------------------- /src/levels/Level11.js: -------------------------------------------------------------------------------- 1 | import React, { 2 | useState, 3 | useRef, 4 | useCallback, 5 | } from 'react'; 6 | 7 | // useCallback 8 | export default function Level11() { 9 | console.log('renderLevel11'); 10 | 11 | const [count, setCount] = useState(0); 12 | 13 | const intervalRef = useRef(null); 14 | 15 | const start = useCallback(() => { 16 | if (intervalRef.current !== null) { 17 | return; 18 | } 19 | 20 | intervalRef.current = setInterval(() => { 21 | setCount(c => c + 1); 22 | }, 500); 23 | }, []); 24 | 25 | const stop = useCallback(() => { 26 | if (intervalRef.current === null) { 27 | return; 28 | } 29 | 30 | clearInterval(intervalRef.current); 31 | intervalRef.current = null; 32 | }, []); 33 | 34 | return ( 35 |
36 | count => {count} 37 | 38 | 39 |
40 | ); 41 | } 42 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Problem 2 | `React Hooks`, unlike `Class Components`, provide low-level building blocks for optimizing and composing applications with minimal boilerplate. 3 | 4 | Without in-depth knowledge, performance problems can arise and code complexity can increase due to subtle bugs and leaky abstractions. 5 | 6 | 7 | # Case Study: Implementing Interval 8 | 9 | This 12 part case study is trying to demonstrate common problems using `React Hooks` and ways to fix them. 10 | 11 | The goal is to implement counter that starts from `0` and increases every `500ms`. Three control buttons should be provided: `start`, `stop` and `clear`. 12 | 13 | # Getting Started 14 | 15 | `> npm install` 16 | 17 | `> npm start` 18 | 19 | Runs the app in the development mode.
20 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 21 | 22 | # Gotchas 23 | 24 | Application is intended to crash in some examples due to memory leaks, infinite recursion, starvation or other bugs. Purpose of this demo is to show common pitfalls with `React Hooks` and how to avoid them. 25 | -------------------------------------------------------------------------------- /src/levels/Level12.js: -------------------------------------------------------------------------------- 1 | import React, { 2 | useState, 3 | useRef, 4 | useCallback, 5 | } from 'react'; 6 | 7 | // custom hook 8 | function useCounter(initialValue, ms) { 9 | const [count, setCount] = useState(initialValue); 10 | const intervalRef = useRef(null); 11 | 12 | const start = useCallback(() => { 13 | if (intervalRef.current !== null) { 14 | return; 15 | } 16 | 17 | intervalRef.current = setInterval(() => { 18 | setCount(c => c + 1); 19 | }, ms); 20 | }, []); 21 | 22 | const stop = useCallback(() => { 23 | if (intervalRef.current === null) { 24 | return; 25 | } 26 | 27 | clearInterval(intervalRef.current); 28 | intervalRef.current = null; 29 | }, []); 30 | 31 | const reset = useCallback(() => { 32 | setCount(0); 33 | }, []); 34 | 35 | return { count, start, stop, reset }; 36 | } 37 | 38 | export default function Level12() { 39 | console.log('renderLevel12'); 40 | 41 | const { count, start, stop, reset } = useCounter(0, 500); 42 | 43 | return ( 44 |
45 | count => {count} 46 | 47 | 48 | 49 |
50 | ); 51 | } 52 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react'; 2 | import Level00 from './levels/Level00'; 3 | import Level01 from './levels/Level01'; 4 | import Level02 from './levels/Level02'; 5 | import Level03 from './levels/Level03'; 6 | import Level04 from './levels/Level04'; 7 | import Level05 from './levels/Level05'; 8 | import Level06 from './levels/Level06'; 9 | import Level07 from './levels/Level07'; 10 | import Level08 from './levels/Level08'; 11 | import Level09 from './levels/Level09'; 12 | import Level10 from './levels/Level10'; 13 | import Level11 from './levels/Level11'; 14 | import Level12 from './levels/Level12'; 15 | 16 | function App() { 17 | const [selectedIndex, setSelectedIndex] = useState(0); 18 | 19 | const levels = [ 20 | Level00, 21 | Level01, 22 | Level02, 23 | Level03, 24 | Level04, 25 | Level05, 26 | Level06, 27 | Level07, 28 | Level08, 29 | Level09, 30 | Level10, 31 | Level11, 32 | Level12, 33 | ]; 34 | 35 | const SelectedComponent = levels[selectedIndex]; 36 | 37 | return ( 38 |
39 |

React Hooks: Interval

40 | 41 | 52 | 53 |
54 | ); 55 | } 56 | 57 | export default App; 58 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 10 | 11 | 15 | 16 | 25 | React App 26 | 27 | 28 | 29 |
30 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl) 104 | .then(response => { 105 | // Ensure service worker exists, and that we really are getting a JS file. 106 | const contentType = response.headers.get('content-type'); 107 | if ( 108 | response.status === 404 || 109 | (contentType != null && contentType.indexOf('javascript') === -1) 110 | ) { 111 | // No service worker found. Probably a different app. Reload the page. 112 | navigator.serviceWorker.ready.then(registration => { 113 | registration.unregister().then(() => { 114 | window.location.reload(); 115 | }); 116 | }); 117 | } else { 118 | // Service worker found. Proceed as normal. 119 | registerValidSW(swUrl, config); 120 | } 121 | }) 122 | .catch(() => { 123 | console.log( 124 | 'No internet connection found. App is running in offline mode.' 125 | ); 126 | }); 127 | } 128 | 129 | export function unregister() { 130 | if ('serviceWorker' in navigator) { 131 | navigator.serviceWorker.ready.then(registration => { 132 | registration.unregister(); 133 | }); 134 | } 135 | } 136 | --------------------------------------------------------------------------------