Created
February 12, 2020 18:39
-
-
Save r3dm1ke/4a44fb2ccfa302042a12fca2af785629 to your computer and use it in GitHub Desktop.
Example with useCallback
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, useMemo, useCallback} from 'react'; | |
| function App() { | |
| const [length, set_length] = useState(3); | |
| const [name, set_name] = useState('John Doe'); | |
| const on_name_changed = useCallback((e) => set_name(e.target.value), []); | |
| const on_length_changed = useCallback((e) => set_length(Number(e.target.value)), []); | |
| return ( | |
| <> | |
| <input value={name} onChange={on_name_changed} /> | |
| <NameDisplay name={name}/> | |
| <hr /> | |
| <input value={length} onChange={on_length_changed} /> | |
| <FibDisplay length={length} /> | |
| </> | |
| ); | |
| } | |
| function FibDisplay({length}) { | |
| const numbers = useMemo(() => { | |
| console.log('Calculating numbers...'); | |
| const result = [1, 1]; | |
| for (let i = 2; i < length; i++) { | |
| result[i] = result[i - 1] + result[i - 2]; | |
| } | |
| return result; | |
| }, [length]); | |
| return <p>{length} numbers of the fibonacci sequence: {numbers.join(', ')}</p>; | |
| } | |
| const NameDisplay = React.memo(function ({name}) { | |
| console.log('Rerendering name...'); | |
| return <p>Your name is {name}</p>; | |
| }); | |
| export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment