I need a variable in the functional component that does not need to be state. There is no problem if I define it outside the component, but if it is inside the component, it will be reset in each with a rendering. Is the definition outside the component is the best way? Do you have a better way?
Asked
Active
Viewed 696 times
0
-
1You can probably use a [ref](https://reactjs.org/docs/refs-and-the-dom.html), using a variable outside the component could become problematic if you're using many instances of the same component – Nick Parsons Sep 23 '21 at 11:17
-
It depends on the context which you didn't provide, looking at the duplicate question should be enough. – Dennis Vash Sep 23 '21 at 11:30
1 Answers
0
outside the component might work. But if you need a variable, that does not change the view, therefore does not need to be state, then it might not belong to the this component and you should rethink your architecture.
This variable might be better given as prop to the component, or handled in a global state.

Simon Hansen
- 622
- 8
- 15
-
Thank you for your answer. Another case is true if I use useRef for the variable I mentioned? – Sajad Speed Sep 23 '21 at 13:23
-
You can use the useRef hook. This will work, but as the name says, it is actually meant to hold a reference to something, for example a child component. But to answer this question, if this is a good approach, you need to provide more context what kind of variable you would like to store and why. – Simon Hansen Sep 23 '21 at 13:33