Last active
May 6, 2019 15:15
-
-
Save igrek8/1428e7483bf60a1c60972763e11fcecc to your computer and use it in GitHub Desktop.
Prevent useCallback rerendering children components https://codesandbox.io/embed/o5o3znl656
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