ReactJS: TypeError: Cannot read properties of null (reading 'useRef')

Viewed 5392

I'm getting this error in my react application in production:
TypeError: Cannot read properties of null (reading 'useRef')
With sourcemap enabled, it shows error in react.production.min.js

What's strange is, I'm getting this only on a particular route. All other routes are working fine (Even though I'm using useRefs in multiple files.).

Since the local build is working fine, I'm unable to reproduce the issue locally.

I tried the following things:

  1. Reverting to previous working commit.
  2. Reinstalling node_modules on prod machine
  3. Switching from Yarn to NPM

I'm using express to host the static build files. Here's the code:

const helmet = require('helmet');
const path = require('path');
const app = express();
const fs = require('fs');

app.disable('x-powered-by');
app.use(helmet.frameguard({ action: 'DENY' }));
app.use(express.static(__dirname));

app.get('*', function (req, res) {
    res.sendFile(path.join(__dirname, 'index.html'), {
        maxAge: 86400000,
    });
});
app.listen(process.env.PORT || 8080, function () {
    console.log(`Frontend start on http://localhost:8080`);
});

Edit: React Component:

import React, { useRef } from 'react';

const ConfigForm = (props) => {
    const scrollTopRef = useRef(null);

    const scrollToTop = () => {
        if (scrollTopRef && scrollTopRef.current) {
            scrollTopRef.current.scrollTo({
                top: 0,
                behavior: 'smooth',
            });
        }
    };

    const onButtonClick = () => {
        scrollToTop();
    }

    return (
        <div className="client-configs" ref={scrollTopRef}>
            <button onClick={onButtonClick}>Scroll To Top</button>
        </div>
    );
}

export default ConfigForm;
2 Answers

The route failed because of one of the packages I was using in the react component. It's package.json mentioned "react": ">=16".

A few days ago, react v18 was released. The prod machine updated this package in node_modules. The package didn't support this and hence failed.

Locally the node_modules is not updated frequently. That being the reason, it worked locally and failed in production.

Lesson learned:

  • Mention package version as ~version or ^version. Check here.
const scrollTopRef = useRef(null);

This essentially means the value of scrollTopRef is null. Then you are using scrollTopRef.current which means you are trying to access current attritube on null which is an error. Hence you need to set scrollTopRef to some meaningful value.

The useRef Hook allows you to persist values between renders.

It can be used to store a mutable value that does not cause a re-render when updated.

Related