Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6214

How can I initialize a class instance in a stateless function component in React?

$
0
0

Using a stateful pattern, I usually initialize a kind of helper class in my constructor and consume its methods in some component lifecycle methods like below:

class StatefulComponent extends Component {  constructor(props) {    super(props);    this.helper = new HelperClass();  }  componentDidMount() {    this.helper.doSomething();  }}

Now, I wanted to convert the same logic into a stateless function component like this:

const StatelessFunction = (props) => {   this.helper = new HelperClass();   useEffect(() => {     this.helper.doSomething();   }, []);}

But I worried when I saw that this component is being called every prop change from the beginning.And this made me think that my class instance is being created over and over. Am I wrong? Is there anything I can do for preventing re-creation of my class and use a ref instead?

I came across useRef but not sure if it fits my case.


Viewing all articles
Browse latest Browse all 6214

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>