10

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.

1
  • Use a ref there. Commented May 18, 2020 at 4:55

2 Answers 2

17

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} />
  );
}
Sign up to request clarification or add additional context in comments.

1 Comment

this was a life saver
0

I think useState is the correct hook in your case. You have an option that is selected by the user and then you do something with the selected value. That's state.

The React docs mention that useRef is not appropriate for storing information you want to display on the screen. In your case you're displaying a list of options and then the user selects one of them, that is information being displayed on the screen, hence useState would be the correct approach.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.