Introduction
We can overwrite _app.js to control the page initialization in Next.js. We can do things like:
- Inject additional data into the page (Get initial props)
- Connect to the Redux provider
- Add global CSS/connect to Styled-Component provider
1.Inject additional data into the page (Get initial props)
SSR (Will disable Automatica Static Optimization)
- The page will be SSR(server-side rendering)
- App currently does not support Next.js Data Fetching methods like getStaticProps or getServerSideProps.
const apiCall = () => {
return new Promise(() => {
setTimeout(() => {
res({testData: 'test'})
}, 1000);
})
};
const page1 = (props) => {
return (
<>
{props.testData}
</>
)
}
page1.getInitialProps = async() => {
const data = await apiCall();
return {..data}
}
export default page1;
import App from 'next/app'
const AppPage = ({Component, pageProps}) => {
return (
{pageProps.add}
<Component {...pageProps}/>
)
}
AppPage.getInitialProps = async (context) => {
const initialProps = App.getInitialProps && await App.getInitialProps(context)
return {pageProps: {add: 'add'}, ...initialProps.pageProps}
}
export default App
What if we would like to use getStaticProps to enable Automatica Static Optimization?
const apiCall = () => {
return new Promise(() => {
setTimeout(() => {
res({testData: 'test'})
}, 1000);
})
};
const page1 = (props) => {
return (
<>
{props.testData}
</>
)
}
export async function getStaticProps(){
const data = awiat apiCall();
return {
props: {
...data
},
};
}
export default page1;
server-side or client-side execution
getInitialProps may execute on the server-side the client-side, it depends on how the page is rendered.
- It will execute on the client-side if the page is rendered by Next/Link | Next/Router
- It will execute on the server-side if the page is rendered by other methods
2.Theme provider (Connect to Styled-Component)
import { ThemeProvider } from 'styled-components';
import Theme from '../components/themes/Theme';
const AppPage = ({Component, pageProps}) => {
return (
<ThemeProvider theme={Theme}>
<Component {...pageProps}/>
</ThemeProvider>
)
}
export default App
3.Redux provider
import store from "../components/store/store";
import { Provider } from 'react-redux';
const AppPage = ({Component, pageProps}) => {
return (
<Provider store={store}>
<Component {...pageProps}/>
</Provider>
)
}
export default App
Articles
There are some of my articles and released projects. Feel free to check if you like!
Top comments (0)