Easy SSR (server side rendering) with react


Posted 4 months ago by Ryan Dhungel

Category: SSR React

Viewed 730 times

Estimated read time: 9 seconds

Ever wanted to implement easy server side rendering with react. React SSR is made easy by react-snapshot. SSR with react-snapshot

 

Code example to fetch todos from open source api and render in your react app

 

import React, { useState, useEffect } from 'react';

const App = () => {
  const [todos, setTodos] = useState([]);
  const [action, setAction] = useState(false);

  const fetchTodosFromServer = async () => {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos');
    const todos = await response.json();
    setTodos(prevState => [...prevState, ...todos]);
  };

  useEffect(() => {
    fetchTodosFromServer();
  }, [action]);

  return (
    <div>
      <button onClick={() => setAction(!action)}>Refetch todos</button>
      <hr />
      <p>Total todos: {todos.length}</p>
      <hr />
      {todos.map(todo => (
        <p key={todo.id}>{todo.title}</p>
      ))}
    </div>
  );
};

export default App;

 

Install react-snapshot

npm i react-snapshot

 

Update your package.json build script

"build": "react-scripts build && react-snapshot"

 

Use react-snapshot's render method instead of ReactDom.render in your index.js

import { render } from 'react-snapshot';
 
 render(
    <App/>,
    document.getElementById('root')
  );

 

Then run npm run build

Run react production build locally

To run production build locally, you should install a package called serve globally by running the following command npm i -g serve

Now run your react app from within your project directory

serve -s build

No open your page and right click to see view page source. You have entire html markup of your page instead of just a div with id of root.