5

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;
Shubham Shinde
  • 136
  • 1
  • 1
  • 8
  • How many refs are you using that broken route? Can you verify if the ref is being initialized correctly in that route? – Nik Apr 04 '22 at 07:07
  • 1
    This is a front end issue, please include the front end react code in question. – Robert May Apr 04 '22 at 07:14
  • The if statement looks ok. You could try changing scrolTopRef = useRef({}). Have you definately rebuilt it and cleared any cache before retesting? Does it work in development mode? Might be worth having a dev build using webpack or nextjs to test it. – Steve Tomlin Apr 04 '22 at 08:19
  • @SteveTomlin Yes tried with useRef({}) too. Still no progress. The build works locally. But the prod fails. – Shubham Shinde Apr 04 '22 at 08:22
  • I have the same problem. It seems related to react 18 and having different instances or versions of react in your app. – Vincent Lecrubier Apr 09 '22 at 10:39
  • https://stackoverflow.com/users/2371254/vincent-lecrubier: can you please expand on this? I am facing this same issue and have react 18 installed. I would not even know how I could use different react versions for production and locally, I only have two different config-files. I have v18 for react and react-dom installed - or can other packages react is working with create this issue too? – Andreas G. Aug 01 '22 at 20:08

3 Answers3

2

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.
Shubham Shinde
  • 136
  • 1
  • 1
  • 8
-1
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.

Harshit Agarwal
  • 2,308
  • 2
  • 15
  • 23
  • 1
    In the React component code, I've already mentioned ref={scrollTopRef} to div element. This fills ref with `{ current: {} }`. Also the code is working locally. – Shubham Shinde Apr 04 '22 at 10:24
-1

The Simple solution for the error is to install the latest version of react-router-dom by writing npm install react-router-dom.

Wongjn
  • 8,544
  • 2
  • 8
  • 24
  • This worked for me - I had two sets of node modules within my react app (Not sure how I didn't notice lol) but I removed the extra node modules and reinstalled react-router-dom and it was all good. However I knew my problem was not the same as this question as I hadn't referenced useRef anywhere but still a useful comment nevertheless. – 36Boxes Jun 08 '23 at 16:36