简体   繁体   中英

How can I dynamically inject a stylesheet in React without the website flickering/reloading?

I have a React application (next.js) that receives a stylesheet from a GET request and then appends it to the webpage.

When I load in the stylesheet the elements that are affected by that stylesheet rerender even if they are not changed. For example the stylesheet includes global styling to h1 tags, however the styling does not differ from the current styling yet it still re-renders.

Is there a way I can prevent this re-render/flicker/reload so that I can provide the user a seamless browsing experience?

Try to use reselect . It supports memoization and I think this is what you are looking for.

React uses shallow compare to compare objects. When an app downloads new data from server, it receives a new object with styles data. React compares it with current props. Even if this object has the same data, for React it is going to be a new a object, so it decides to re-render the component.

Using reselect we are saving last object, that we received before and compare it with the new one. If the new object has exactly the same structure, reselect will send the old object (memoized object) to the component. This way the component will receive the same object and it will not be re-rendered.

Usually reselect is used with Redux, but according their FAQ it can be used independently:

Q: Can I use Reselect without Redux? A: Yes. Reselect has no dependencies on any other package, so although it was designed to be used with Redux it can be used independently. It is currently being used successfully in traditional Flux apps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM