React useSSR Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the use of the useSSR hook in React. This hook allows us to check whether our code is running on the browser or the server, and provides additional information about the environment such as the availability of workers, event listeners, and viewport. By the end of this lab, you will have a better understanding of how to write React code that is optimized for different environments.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react(("`React`")) -.-> react/PerformanceOptimizationGroup(["`Performance Optimization`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/conditional_render("`Conditional Rendering`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") react/PerformanceOptimizationGroup -.-> react/memoization("`Memoization with useMemo`") subgraph Lab Skills react/jsx -.-> lab-38410{{"`React useSSR Hook`"}} react/conditional_render -.-> lab-38410{{"`React useSSR Hook`"}} react/hooks -.-> lab-38410{{"`React useSSR Hook`"}} react/use_state_reducer -.-> lab-38410{{"`React useSSR Hook`"}} react/memoization -.-> lab-38410{{"`React useSSR Hook`"}} end

React useSSR Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

To check if the code is running on a browser or server, create a custom hook that uses typeof, Window, Window.document, and Document.createElement() to determine if the DOM is available. Use the useState() hook to define the inBrowser state variable and the useEffect() hook to update it and clean up at the end. Use the useMemo() hook to memoize the return values of the custom hook.

Here is the code:

const isDOMavailable = !!(
  typeof window !== "undefined" &&
  window.document &&
  window.document.createElement
);

const useSSR = () => {
  const [inBrowser, setInBrowser] = React.useState(isDOMavailable);

  React.useEffect(() => {
    setInBrowser(isDOMavailable);
    return () => {
      setInBrowser(false);
    };
  }, []);

  const useSSRObject = React.useMemo(
    () => ({
      isBrowser: inBrowser,
      isServer: !inBrowser,
      canUseWorkers: typeof Worker !== "undefined",
      canUseEventListeners: inBrowser && !!window.addEventListener,
      canUseViewport: inBrowser && !!window.screen
    }),
    [inBrowser]
  );

  return useSSRObject;
};

const SSRChecker = (props) => {
  const { isBrowser, isServer } = useSSR();

  return <p>{isBrowser ? "Running on browser" : "Running on server"}</p>;
};

ReactDOM.createRoot(document.getElementById("root")).render(<SSRChecker />);

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the React useSSR Hook lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like