Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance variable reset everytime component re-render in ReactJs

Tags:

reactjs

I created one functional component and declared some variables in it.

const Foo = (props) => {
  let instanceVariable = null;

  const selectValue = (value) => {
    instanceVariable = value;
  }

  const proccessVariable = () => {
   // Use instanceVariable and do some task
  }

  return(
    <SelectionOption onChange={selectValue} />
  );
}

I observed that whenever parent component of Foo is re-rendered or sometime Foo itself re-renders instanceVariable set back to null. Instead of this I want to save selectedValue init and proccess it later on proccessVariable() method.

If I set instanceVariable as state it will work and there is no need of state to just hold the selected value.

I know useEffect(()=>{}, []) only run one time but how can I declare instanceVariable there and use it in other functions.

Can you please let me know what I'm doing wrong.

like image 506
Azeem Haider Avatar asked Jan 25 '23 01:01

Azeem Haider


1 Answers

Since you declare a variable directly in your functional component, its value is reset everytime your component re-renders. You can make use of useRef to declare instance variables in functional component

const Foo = (props) => {
  let instanceVariable = useRef(null);

  const selectValue = (value) => {
    instanceVariable.current = value; // make sure to use instanceVariable.current
  }

  const proccessVariable = () => {
   // Use instanceVariable.current and do some task
  }

  return(
    <SelectionOption onChange={selectValue} />
  );
}
like image 160
Shubham Khatri Avatar answered May 19 '23 11:05

Shubham Khatri