Home > Back-end >  Is it possible to use objects declared in useeffect hook?
Is it possible to use objects declared in useeffect hook?

Time:01-25

I want to use object declared in useEffect hook, like

function App(){
  useEffect(() => {
    let myObject = .....
  }
  
  myObject.myFunction()
}

but IDE gives me an error that myObject is not defined...

I assume that it is not a good way to lead re-rendering objects declared in useEffect hook, but anyway, is there any way to use objects declared in useEffect hook?

CodePudding user response:

I don't think so, because it's in different scope.

it would be ok to use state instead, because when useEffect call and object change, you wont get new value in object

like this :

function App(){
  const [myObject,setMyObject] = useState()
  useEffect(() => {
    setMyObject(...)
  },[])

  myObject?.myFunction()
}

CodePudding user response:

First your code is wrong. It's not useeffect it's useEffect, so:

useeffect(() => {
  let myObject = .....
}

should be:

useEffect(() => {
  let myObject = .....
}

Second you would use useState in this scenario:

const [ myObject, setMyObject ] = useState()

  useEffect(() => {
    setMyObject(...)
  }, [])

  myObject?.myFunction()

Third make sure you're importing them correctly with something like:

import React, { useState, useEffect } from 'react'

function So75221887() {
  const [ myObject, setMyObject ] = useState()

  useEffect(() => {
    setMyObject(...)
  }, [])

  myObject?.myFunction()
}

export default So75221887
  • Related