0

Here is my react component... I can't figure out why nyVariable says that it is not defined...

import React from "react";
import { useEffect } from "react";

const Component = () => {

  useEffect(() => {
    const myVariable = "Jim"
  }, []);

  return(<div>{myVariable}</div>) 
};

export default Component;

Thanks!

Newbie
  • 31
  • 6
  • 1
    Does this answer your question? [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – David Aug 15 '22 at 17:27
  • To be more specific about the code shown... The variable `myVariable` is defined *inside a function* (the callback passed to `useEffect`), so it only exists *within that function*. But what is the purpose of `useEffect` here at all? None. Remove it, and just define the variable directly in the component. – David Aug 15 '22 at 17:31
  • Thanks, I can't believe I forgot that – Newbie Aug 15 '22 at 17:32

2 Answers2

1

A variable created inside a useEffect can not be accessed from outside the useEffect. I would recommend looking into how a useEffect and useState work.

Try something like this:

import React from "react";
import { useEffect, useState } from "react";

const Component = () => {
  const [state, setState] = useState("");
  useEffect(() => {
    setState("Jim");
  }, []);

  return(<div>{state}</div>) 
};

export default Component;

This will create a state variable that contains an empty string. Then upon the components first render, will set the state to "Jim".

Matt B.
  • 49
  • 3
0

Your are getting undefined because of the scope rule in javascript. Try to do it this way.

import React from "react";
import { useEffect } from "react";

const Component = () => {
  const myVariable = "";

  useEffect(() => {
    myVariable = "Jim"
  }, []);

  return(<div>{myVariable}</div>) 
};

export default Component;

Because your defining your variable inside useEffect (Function) it is available only inside this function. you will not be able to access it outside. This is why I declared it outside first and then updated it value inside the useEffect hook.

Wayne Celestin
  • 149
  • 1
  • 6