Created
May 7, 2020 16:49
-
-
Save zackdotcomputer/b1b7576b2490a64bd6536ce7b828a916 to your computer and use it in GitHub Desktop.
Fixed index.tsx for reduced-context-bug - Wait until mounting
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
import React, { createContext, useContext, useEffect, useState } from "react"; | |
import { useWindowSize } from "react-use"; | |
const DisplayContext = createContext<"normal" | "compact">("normal"); | |
export default function Parent() { | |
const { width } = useWindowSize(); | |
const [windowSizeDisplayContext, setWindowSizeDisplayContext] = useState< | |
"normal" | "compact" | |
>("normal"); | |
useEffect(() => { | |
if (width !== Infinity) { | |
setWindowSizeDisplayContext(width > 800 ? "normal" : "compact"); | |
} | |
}, [width]); | |
return ( | |
<div className="container"> | |
<DisplayContext.Provider value={windowSizeDisplayContext}> | |
<Child /> | |
</DisplayContext.Provider> | |
</div> | |
); | |
} | |
const Child: React.FC = () => { | |
const displayContext = useContext(DisplayContext); | |
return ( | |
<div> | |
<p hidden={displayContext === "normal"}>Compact</p> | |
<p hidden={displayContext === "compact"}>Normal</p> | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment