I decided to use React's ContextAPI to store authenticated user data.
I've implemented a custom App component and wrote a getInitialProps function to retrieve user's data from the backend.
class MyApp extends App {
render() {
const { Component, pageProps, authenticated, user } = this.props;
return (
<AuthProvider authenticated={authenticated}>
<UserProvider userData={user}>
<Component {...pageProps} />
</UserProvider>
</AuthProvider>
);
}
}
MyApp.getInitialProps = async (appContext) => {
let authenticated = false;
let user = null
const request = appContext.ctx.req;
if (request) {
request.cookies = cookie.parse(request.headers.cookie || '');
authenticated = !!request.cookies.sessionid;
if (authenticated){
user = await getCurrentUserData(request.headers.cookie)
}
}
// Call the page's `getInitialProps` and fill `appProps.pageProps`
const appProps = await App.getInitialProps(appContext);
return { ...appProps, authenticated, user };
};
export default MyApp;
What's concerns me the most is that getCurrentUserData is called every time a page is being rendered, so there is always one extra API call.
Is it good practice to do so? Should I store user's data in a cookie, and update context from there? How can I optimize this solution?
Thanks