Skip to content

Instantly share code, notes, and snippets.

@zackdotcomputer
Created May 7, 2020 16:49
Show Gist options
  • Save zackdotcomputer/b1b7576b2490a64bd6536ce7b828a916 to your computer and use it in GitHub Desktop.
Save zackdotcomputer/b1b7576b2490a64bd6536ce7b828a916 to your computer and use it in GitHub Desktop.
Fixed index.tsx for reduced-context-bug - Wait until mounting
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