React Interview Questions

39 Questions
React.js

React.js

FrontendWeb Development

Question 23

What is server-side rendering (SSR) and how does it benefit a React application?

Answer:

Server-Side Rendering (SSR) is a technique where the HTML for a web page is generated on the server rather than in the browser. In the context of a React application, SSR means that the initial rendering of the React components happens on the server. When a user requests a page, the server generates the HTML for that page and sends it to the browser. The browser then downloads the JavaScript, which takes over to make the page interactive.

How SSR Works with React

  1. Request: A user requests a URL.
  2. Server Processing: The server processes the request and renders the React components to HTML.
  3. HTML Response: The server sends the fully rendered HTML to the client.
  4. Hydration: Once the client receives the HTML, React takes over, attaches event handlers, and makes the page interactive. This process is called hydration.

Benefits of SSR in a React Application

  1. Improved Performance:

    • Faster Initial Load: Since the server sends a fully rendered HTML page, the browser can display content faster, leading to a quicker first meaningful paint.
    • Better for SEO: Search engines can index the content more effectively because the HTML is fully rendered, improving the search engine optimization (SEO) of the application.
  2. Enhanced User Experience:

    • Perceived Performance: Users perceive the application as faster because they see the content sooner, even though the JavaScript might still be loading in the background.
    • Accessibility: SSR can improve the accessibility of your application by ensuring that content is available without requiring JavaScript to be fully loaded.
  3. SEO Benefits:

    • Search Engine Crawlers: Some search engines struggle with or are unable to execute JavaScript. SSR ensures that these crawlers see the full content of the page, improving the chances of your content being indexed correctly.
  4. Social Media Sharing:

    • Open Graph and Twitter Cards: Social media platforms use metadata in the HTML to generate previews when links are shared. SSR ensures that this metadata is present and correct, improving the appearance and effectiveness of shared links.

Implementing SSR with React

To implement SSR with React, you can use frameworks like Next.js, or you can set it up manually with Node.js and Express.

Example with Next.js

Next.js is a popular framework for React applications that supports SSR out of the box.

  1. Install Next.js:

    npx create-next-app my-app
    cd my-app
  2. Create a Page:

    // pages/index.js
    import React from 'react';
    
    const HomePage = ({ data }) => {
      return (
        <div>
          <h1>Server-Side Rendered Page</h1>
          <p>{data}</p>
        </div>
      );
    };
    
    export async function getServerSideProps() {
      // Fetch data from an API or database
      const data = "Hello, this is server-side rendered!";
      return {
        props: { data },
      };
    }
    
    export default HomePage;

In this example, the getServerSideProps function fetches data on the server and passes it as props to the HomePage component. Next.js handles the rendering of this component on the server and sends the fully rendered HTML to the client.

Example with Node.js and Express

For a more custom setup, you can use Node.js and Express to implement SSR.

  1. Set Up the Server:

    npm init -y
    npm install express react react-dom @babel/core @babel/preset-env @babel/preset-react
  2. Configure Babel:

    // .babelrc
    {
      "presets": ["@babel/preset-env", "@babel/preset-react"]
    }
  3. Create the Server and Render React:

    // server.js
    const express = require('express');
    const React = require('react');
    const ReactDOMServer = require('react-dom/server');
    
    const app = express();
    
    const Html = ({ body, title }) => `
      <!DOCTYPE html>
      <html>
        <head>
          <title>${title}</title>
        </head>
        <body>
          <div id="root">${body}</div>
          <script src="/bundle.js"></script>
        </body>
      </html>
    `;
    
    const App = () => {
      return <h1>Hello from Server-Side Rendering!</h1>;
    };
    
    app.get('/', (req, res) => {
      const body = ReactDOMServer.renderToString(<App />);
      const html = Html({ body, title: 'SSR with React' });
      res.send(html);
    });
    
    app.listen(3000, () => {
      console.log('Server is running on port 3000');
    });

In this example, the Express server renders the App component to a string and injects it into an HTML template. The server then sends this HTML to the client.

Conclusion

Server-Side Rendering (SSR) in React can significantly improve performance, SEO, and user experience by rendering pages on the server and sending fully rendered HTML to the client. Frameworks like Next.js simplify the implementation of SSR, while custom setups with Node.js and Express provide more control. By leveraging SSR, you can create faster, more accessible, and SEO-friendly React applications.

Recent job openings