Created
May 6, 2019 15:14
-
-
Save igrek8/fa5b1bedcecb997797e6f088c1d4a20c to your computer and use it in GitHub Desktop.
Prevent useCallback rerendering children components
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, useRef, useCallback } from "react"; | |
| import Button from "./Button"; | |
| function App() { | |
| const [state, setState] = useState(""); | |
| const ref = useRef(state); | |
| const handleChange = useCallback(event => { | |
| ref.current = event.target.value; | |
| setState(event.target.value); | |
| }, []); | |
| const handleClick = useCallback( | |
| event => { | |
| event.preventDefault(); | |
| alert(ref.current); | |
| }, | |
| [ref] | |
| ); | |
| return ( | |
| <form onSubmit={handleClick}> | |
| <input onChange={handleChange} /> | |
| <Button onClick={handleClick} /> | |
| </form> | |
| ); | |
| } | |
| export default App; |
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 { useRef, useState, useCallback } from "react"; | |
| function useMemoState(...args) { | |
| const [state, _setState] = useState(...args); | |
| const memoState = useRef(state); | |
| const setState = useCallback( | |
| nextState => { | |
| memoState.current = nextState; | |
| _setState(nextState); | |
| }, | |
| [memoState] | |
| ); | |
| return [memoState, setState]; | |
| } | |
| export default useMemoState; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment