Skip to content

Instantly share code, notes, and snippets.

@AndrewRayCode
Created July 14, 2019 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewRayCode/1b1a127b012aa879ef95d82f74d1c29f to your computer and use it in GitHub Desktop.
Save AndrewRayCode/1b1a127b012aa879ef95d82f74d1c29f to your computer and use it in GitHub Desktop.
// Build a hook to register a callback to run every frame (subscribe(...))
// to copy some state into our component if some condition is met
function useStateCheck() {
const {
state,
subscribe
} = useContext(context);
const [_, setState] = useState(state);
useEffect(() => {
const unsubscribe = subscribe((newState) => {
if (someCondition) {
// For some reason, calling this setState here (used in component below) causes the
// component to unmount and remount.
setState(newState);
}
);
return () => unsubscribe();
}, []);
return state;
}
function MyComponent() {
const myState = useStateCheck();
useEffect(() => () => console.log("This gets logged when the hook sets state, and I don't know why"));
return <div>
...
</div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment