Created
July 14, 2019 20:31
-
-
Save AndrewRayCode/1b1a127b012aa879ef95d82f74d1c29f to your computer and use it in GitHub Desktop.
This file contains 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
// 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