Skip to content

Instantly share code, notes, and snippets.

@bitttttten
Created June 16, 2019 15:04
Show Gist options
  • Select an option

  • Save bitttttten/881aafec1c9fe776d15ec0cc8120b7f2 to your computer and use it in GitHub Desktop.

Select an option

Save bitttttten/881aafec1c9fe776d15ec0cc8120b7f2 to your computer and use it in GitHub Desktop.
useEffect and syncing
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