I started learning React and now I'm trying to understand what is the purpose of the index.js
and App.js
which are created by by running create-react-app.
Why can't we just use, for example. App.js
?
I've read that App.js usually used as a main entry point to the application, but auto-generated code of index.js
seems like a part of main entry point:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
I saw a similar questions for react native but I want to know about this in react in general.
index.js
is the traditional and actual entry point for all node apps. Here in react it just has code of what to render and where to render.
App.js
on the other hand has the root component of the react app because every view and component are handled with hierarchy in React, where <App />
is the top most component in hierarchy. This gives you feel that you maintain hierarchy in your code starting from App.js
.
Other than that, you can have the App logic in index.js
file itself. But it's something related to conventions followed by the community using the library or framework. It's always feel good to go along the community.
create-react-app
use a plugin for webpack that name is html-webpack-plugin and this plugin use index.js
for entrypoint like below :
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: 'index.js',
output: {
path: __dirname + '/dist',
filename: 'index_bundle.js'
},
plugins: [
new HtmlWebpackPlugin()
]
}
this plugin use for generating html file.