Created
June 16, 2019 15:04
-
-
Save bitttttten/881aafec1c9fe776d15ec0cc8120b7f2 to your computer and use it in GitHub Desktop.
useEffect and syncing
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 { useEffect, useRef, useState } from 'react'; | |
| export default function AjaxToggle() { | |
| const [checked, setChecked] = useState(false); | |
| const firstRender = useRef(true); | |
| function syncWithServer(checked) { | |
| // ... | |
| } | |
| useEffect(() => { | |
| if (firstRender.current) { | |
| firstRender.current = false; | |
| return; | |
| } | |
| syncWithServer(checked); | |
| }, [checked]); | |
| return ( | |
| <input | |
| type="checkbox" | |
| checked={checked} | |
| onChange={() => setChecked(!checked)} | |
| /> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment