This article is about fixing ReferenceError Cannot access 'varName' before initialization in Facebook Create React App
  • 29-Jan-2023
Lightrun Team
Author Lightrun Team
Share
This article is about fixing ReferenceError Cannot access 'varName' before initialization in Facebook Create React App

ReferenceError: Cannot access ‘varName’ before initialization in Facebook Create React App

Lightrun Team
Lightrun Team
29-Jan-2023

Explanation of the problem

The problem is that a React app running on React v17 and using react-scripts 3.4.4 was upgraded to use react-scripts 4.0.0, and upon the first load in development, an error occurred that did not exist before the upgrade.

The error is related to a custom hook called useSnackbar. The useSnackbar.js file exports a SnackbarProvider and the useSnackbar hook. The useSnackbar hook is re-exported through a hooks/index.js file as shown in the following code block:

// hooks/index.js
export {useSnackbar} from "./useSnackbar";

This hook is then used throughout the app. The error message suggests that the problem may be related to hot refresh. The following code block shows an example of how the useSnackbar hook is used in a component:

import { useSnackbar } from './hooks';

function MyComponent() {
  const { showSnackbar } = useSnackbar();

  return (
    <button onClick={() => showSnackbar('Hello, World!')}>
      Show Snackbar
    </button>
  );
}

The expected behavior is that the application runs correctly in development using hot refresh. However, the actual behavior is that the app errors on load. A reproducible demo of the problem is not available outside of the application. The current version of create-react-app is 4.0.0 and it is running from C:\Users\MattCorner\AppData\Roaming\npm-cache_npx\11504\node_modules\create-react-app . The system info is Windows 10 10.0.19041, CPU: (12) x64 Intel® Core™ i7-9750H CPU @ 2.60GHz, Node: 14.8.0, npm: 6.14.8, Browsers: Edge: Spartan (44.19041.423.0), Chromium (86.0.622.51) Internet Explorer: 11.0.19041.1, npmPackages: react: Not Found react-dom: Not Found react-scripts: Not Found npmGlobalPackages: create-react-app: Not Found

Troubleshooting with the Lightrun Developer Observability Platform

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.

  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

Problem solution for ReferenceError: Cannot access ‘varName’ before initialization in Facebook Create React App

The “ReferenceError: Cannot access ‘varName’ before initialization” is a common error that can occur when using Facebook’s Create React App (CRA) framework. This error occurs when a variable is accessed before it has been initialized.

One solution to this problem is to ensure that the variable is properly initialized before it is accessed. This can be done by declaring the variable and assigning it a value before it is used. For example, the following code block illustrates how to properly initialize a variable called “varName” before it is accessed:

let varName = '';

function MyComponent() {
  varName = 'Hello, World!';
  return <div>{varName}</div>;
}

Another solution is to use the useState hooks from React, which allows you to manage state in functional components. This approach allows you to declar a variable and set its initial value in one step, like this:

import { useState } from 'react';

function MyComponent() {
  const [varName, setVarName] = useState('');

  return (
    <>
      <button onClick={() => setVarName('Hello, World!')}>
        Show varName
      </button>
      <div>{varName}</div>
    </>
  );
}

It is also important to keep in mind that in JavaScript, let and const are block-scoped, whereas var is function-scoped. So if you are using let or const to declare a variable, make sure it’s in the right scope.

It is also important to ensure that any dependencies are up to date, and that the version of React and React-scripts are compatible. Finally, make sure to check for any missing or misnamed imports or exports, as those can also cause errors related to variable initialization.

Other popular problems with Create React App

Problem: “TypeError: Cannot read property ‘map’ of undefined”

This error occurs when trying to use the .map() method on an undefined value. This can happen when trying to map over the elements of an array that has not been properly initialized or has not been loaded yet.

Solution:

Make sure that the array is properly initialized before it is accessed. For example, the following code block illustrates how to properly initialize an array called “myArray” before it is accessed:

let myArray = [];

function MyComponent() {
  useEffect(() => {
    fetch('https://my-api.com/data')
      .then(response => response.json())
      .then(data => setMyArray(data))
  }, []);

  return (
    <>
      {myArray.map(item => (
        <div key={item.id}>{item.name}</div>
      ))}
    </>
  );
}

Another solution is to use the useState hooks from React, which allows you to manage state in functional components. This approach allows you to declar a variable and set its initial value in one step, like this:

import { useState } from 'react';

function MyComponent() {
  const [myArray, setMyArray] = useState([]);

  useEffect(() => {
    fetch('https://my-api.com/data')
      .then(response => response.json())
      .then(data => setMyArray(data))
  }, []);

  return (
    <>
      {myArray.map(item => (
        <div key={item.id}>{item.name}</div>
      ))}
    </>
  );
}

Problem: “Invariant Violation: Could not find “store” in either the context or props of “Connect(MyComponent)””

This error occurs when trying to use the connect() function from the react-redux library without properly providing the store as a context. This can happen when the <Provider> component from react-redux is not being used or is not being used correctly.

Solution:

Make sure that the <Provider> component is being used and that it is being passed the store as a prop. For example, the following code block illustrates how to properly use the <Provider> component:

import { Provider } from 'react-redux';
import store from './store';

function MyApp() {
  return (
    <Provider store={store}>
      <MyComponent />
    </Provider>
  );
}

Another solution is to use the useEffect hook to get the store from the context and pass it to the component that needs it.

import { useEffect, useContext } from 'react';
import { StoreContext } from './store';

function MyComponent() {
  const store = useContext(StoreContext);

  // use the store here
}

Problem: Can’t perform a React state update on an unmounted component”

This error occurs when trying to set a state on a component that has been unmounted. In Create React App, this error may occur when using the “setState” method in a component’s lifecycle method, such as “componentDidUpdate” or “componentWillUnmount”.

Solution:

To solve this issue, make sure to check if the component is still mounted before updating the state. You can use a variable such as “isMounted” to check if the component is still mounted. For example:

class MyComponent extends React.Component {
  state = {
    value: 0
  }
  _isMounted = false;
  
  componentDidMount() {
    this._isMounted = true;
  }

  componentWillUnmount() {
    this._isMounted = false;
  }

  handleClick = () => {
    if (this._isMounted) {
      this.setState({ value: this.state.value + 1 });
    }
  }

  render() {
    return <button onClick={this.handleClick}>{this.state.value}</button>;
  }
}

This way, you make sure that you only update the state if the component is still mounted.

A brief introduction to Create React App

Facebook Create React App (CRA) is a tool for creating and managing React applications. It provides a set of tools and configurations for developing and building React applications, making it easy for developers to get started with creating React apps.

CRA abstracts away the complex configuration that is required to set up a React application, such as webpack, babel and other development tools. It also provides a set of scripts for development, testing, and production builds that can be run with a simple command-line interface. Additionally, it comes with a set of default configurations, such as development and production environments, which can be easily customized to suit the needs of the application. With CRA, developers can focus on writing code, rather than worrying about configuring their development environment.

Most popular use cases for Create React App

  1. Creating and building React applications: Create React App is a tool that can be used to create and build React applications. It provides a set of tools and configurations that make it easy for developers to get started with creating React apps.
  2. Abstracting away complex configuration: Create React App abstracts away the complex configuration that is required to set up a React application, such as webpack, babel and other development tools. This makes it easy for developers to focus on writing code, rather than worrying about configuring their development environment.
npx create-react-app my-app
  1. Providing a development, testing and production build scripts: Create React App also provides a set of scripts for development, testing, and production builds that can be run with a simple command-line interface. These scripts can be used to build, test and deploy React applications, making the development process more streamlined and efficient.
npm start  # starts development server
npm test   # runs tests
npm run build  # creates production build
Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.