Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does the code outside React Component class in a JS file run?

Say I have a JS file contains 2 React Component class definition and a bunch of other things:

// a file called OuterComponent.react.js

import xxx from xxx;
import yyy from yyy;

// When does these run?
let a = 0;
a = 1;

export default class OuterComponent extends React.PureComponent<> {
  render() {
    return (
      <View>
       <InnerComponent />
      </View>
    );
  }
}

class InnerComponent extends React.PureComponent<> {
  //... something
}

Questions

  1. When will the declaration and value setting code for 'a' run? Does it run when this file is imported/required by other files?

  2. Can I have some flag in this file and changes from time to time, and then read the value of this flag from many other files? (like a singleton manager?) If I can, how do I export it and import it?

  3. What does creating multiple files actually mean? (except that it breaks huge chunk of code into small chunks for better readability) Does it make any other difference?

like image 970
Hua Avatar asked Oct 20 '25 01:10

Hua


1 Answers

Question 1: When will the declaration and value setting code for 'a' run? Does it run when this file is imported/required by other files?

Runs the first time the file is imported. It is not executed on subsequential imports.

Question 2: Can I have some flag in this file and changes from time to time, and then read the value of this flag from many other files? (like a singleton manager?) If I can, how do I export it and import it?

You can.

Exporting:

export let a = 0;

Importing:

import { a } from './filename.js';

Question 3: What does creating multiple files actually mean? (except that it breaks huge chunk of code into small chunks for better readability) Does it make any other difference?

  • Breaks code into small chunks;
  • Allows reuse; and
  • Enables encapsulation of non-exported variables/functions.

--

Check a demo of modules usage: http://plnkr.co/edit/0ImgQj2KzLj9O1D63Gq9?p=preview

Notice how a.js is loaded only once, even though it is imported both by b.js and c.js. Also see how it is exported and imported, and how when it changes, the change is picked up in other modules.

like image 188
acdcjunior Avatar answered Oct 21 '25 17:10

acdcjunior