Mohammad
Mohammad

Reputation: 395

How can I implement a real partial update with ReactJS?

I had a job interview and the recruiter asked me about "handle the partial updates and manage application size"

For example he explained and displayed a SPA that size was 8MB and he said it's not ideal and perfect !?!?

And he said we should manage the application size with different methods !?

For a test, after the interview session I checked the linkedin website with google chrome DevTools. after any requests I saw response who that was html web page (Html, Css, JS) and apparently linkedin after each requests appends html response to page who it's an idea to control SPA size !

So I have a question, by default in create-react-app package we have webpack to create web modules and that load all components to one bundle.js and this js file will be heavy for 40 or more component. maybe 10MB or more than ...

How can I implement a real and optimized SPA structure with a perfect and accurate partial update method ?

Unfortunately I just know a little of English, please forgive me if I had mistake to write English :-) ;-)

Thank you

Upvotes: 4

Views: 2928

Answers (2)

Hem
Hem

Reputation: 132

I suggest you look at lazy loading concepts in ReactJs documentation. It is basically importing only when need arrives and reduces bundle size.

ReactJS Code splitting Documentation

Upvotes: 0

supra28
supra28

Reputation: 1636

I think what you are looking for is Dynamic imports or asynchronously loading components(or more code) whenever needed. There are various ways you can do this like

  • Load when the user scrolls down towards the components
  • Only Load the component when a user clicks a button (ex. a Modal)
  • Load the component after the initial critical data is already rendered(ex. only ldownload the code for the component after its parent component is already loaded and rendered to the dom).

The last example can be done like this :

class Dynamic extends Component {
  constructor(props) {
    super(props);
    this.state = { module: null };
  }
  componentDidMount() {
    const { path } = this.props;
    import(`${path}`)
      .then(module => this.setState({ module: module.default }))
  }
  render() {
    const { module: Component } = this.state; // Assigning to new variable names @see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
    return(
      <div>
        {Component && <Component />}
      </div>
    )
  }
}

What the above code is doing is loading the Component code after its parent component is already loaded by importing it in component did mount.

This code-splitting method is currently

supported by create-react-app.

read more here

Also check this react-loadable

Upvotes: 6

Related Questions