How to prevent unnecessary render when fetching static content?

Viewed 279

When I use react hooks I declare my state to be like this:

const [entities,setEntities] = useState([])

Then I make an api call to the server that return static content that never changes. I setEntities(fetchedData) and what is actually happening is that I render the component twice - Once when the array is empty and the second time is when the data arrives. The data is static and it never changes. Was wondering if there is a certain way to prevent this unnecessary render? I thought the solution will be to make the api call on componentWillMount but there isn't any parallel solution with hooks to this, as this method is not used anymore.

3 Answers

If you really want to render that component only once, you could move the fetching logic to it's parent.

In parent:

fetchData();
entities; // where the data from request is stored

Then use a basic render condition:

{entities && <Child entities={entities} />} 

Then, wrap the Child component with React.memo to avoid re-renders if parent re-rendered.

export const Child = React.memo(() => {
  ...
});

Finally, what is most important - operate over props, do not save it inside state. So if you want to do something with the entities, use it as props.

{props.entities.map(...)}

The Child will render only once, when entities data is received from API. If only you won't call API anymore, it will stay at it is.

Whenever you make a call to the client from a react component the double rendering will happen. For that particular case, I recommend you to use ReactDOMServer

The ReactDOMServer object enables you to render components to static markup. Typically, it’s used on a Node server:

Or if you did'nt start your project yet you could try using a server-side render framework like nextjs

Related