cannot read properties of null (reading 'usestate')
11 April 2023
Errors
- Unhandled Runtime Error
TypeError: Cannot read properties of null (reading 'useState') - "Invalid hook call. Hooks can only be called inside of the body of a function component."
Reason
- While integrating a React submodule into a Next.js project, you could experience an issue with two occurrences of React stacking at the same time.
- This is because, submodule and Next project have their own instance of the React in their node_modules.
- The problem arises when the code from your submodule tries to use its instance of React, while the rest of your Next.js project uses a different instance.
Solution
Modifying the Webpack Configuration.
To solve th above issue, we need to update the webpack configuration of the NextJS.
Add the following webpack configuration inside next.config.js.
const path = require("path");
module.exports = {
webpack: (config, options) => {
if (options.isServer) {
config.externals = ["react", ...config.externals];
}
config.resolve.alias["react"] = path.resolve(__dirname, ".", "node_modules", "react");
return config;
}
}
What does this code do?
if (options.isServer)
ensures changes are applied to server-side build.config.externals = ['react', ...config.externals]
adds 'react' to external dependencies which means it will not be included into the final bundle of the NextJs.config.resolve.alias['react'] = path.resolve(__dirname, '.', 'node_modules', 'react')
instructs webpack to resolve all the imports of 'react' to the version installed in root node_modules, eliminating any duplication.