Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it anti-pattern to 'require' inside componentWillMount?

Tags:

reactjs

Is it anti-pattern to 'require' inside componentWillMount? I'm trying to dynamically load a locale based on the current user region.

componentWillMount(){
 if (localStorage.getItem('locale') === 'da') {
  require('moment/locale/da')
  moment.locale('da')
 }
}

Thank you!

like image 987
gnifrus Avatar asked Feb 05 '18 13:02

gnifrus


1 Answers

Depending on what tool to bundle the code you're using, the result may vary. If you use Webpack, it will resolve "require" and "import" in-place, not skipping class methods or anything. It means you won't really benefit much from this. The bundle size won't be optimal, but you'll likely increase the chance of shooting in the foot.

However, in Webpack 3, there's a feature called lazy loading in Webpack that allows you to require a module on the run-time. Webpack will take care of putting all the necessary JS code on the run-time in user's browser to require the module from server and execute it (think creating a "script" element and appending it to document).

There's a note on lazy loading in official Webpack documentation that points at potential difference in implementation of this feature across different libraries. With this, the code would look like

async componentDidMount() { // <- note that componentWillMount isn't the best place to lazy-load a remote module, see @TryingToImprove's comment
  const da = await import('moment/locale/da'); // <- Webpack will add its magic here
  moment.locale(da);
}

Also, read more on dynamic imports.

So, answering your question

Is it anti-pattern to 'require' inside componentWillMount?

I'm afraid it still is in early 2018, at least in a way you described, and unless special care is taken of it.

ESLint actually has a rule for that, global-require, that automatically waves a flag when an "import" or "require" statement stands anywhere except global scope.

like image 81
rishat Avatar answered Oct 20 '22 01:10

rishat