Skip to content

Instantly share code, notes, and snippets.

@mskoroglu
Created November 5, 2019 21:53
Show Gist options
  • Save mskoroglu/347471106b24b752d578150da63fd358 to your computer and use it in GitHub Desktop.
Save mskoroglu/347471106b24b752d578150da63fd358 to your computer and use it in GitHub Desktop.
React SSR ClientSide component
import React from "react";
export const ClientSide = ({ children, placeholder, delay }) => {
const [showState, setShowState] = React.useState(false);
const delayInMillis = delay !== undefined ? parseInt(delay) : 0;
React.useEffect(() => {
const timeout = setTimeout(() => setShowState(true), delayInMillis);
return () => clearTimeout(timeout);
}, []);
return showState ? children : placeholder || <React.Fragment></React.Fragment>;
};
export default ClientSide;
import React from "react"
import ClientSide from "../src/ClientSide"
const IndexPage = () => (
<div>
<p>rendered on the server</p>
<ClientSide>
<p>rendered on the client</p>
</ClientSide>
<ClientSide placeholder={<span>loading...</span>}>
<p>with placeholder</p>
</ClientSide>
<ClientSide delay="1500">
<p>with delay (1500ms)</p>
</ClientSide>
</div>
)
export default IndexPage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment