Search code examples
reactjsreact-hooksthisreact-functional-componentreact-class-based-component

'this' inside a function of a class component (react)


I am converting class components into functional components and get the error during removing 'this'.

The original project (with class components) runs well. But when I remove 'this' from 'this.intervalID', it shows an error

It confuses me, because 'intervalID' is declared nowhere in the project (neither state, props), only appears in the code below (in the functions startInterval() and stopInterval).

Maybe I have not yet understood fully how 'this' is used in a class component. Can anyone help? And maybe also help me: how to convert these kind of 'this' in conversion to a functional component.

 startInterval = () => {
    this.intervalID = setInterval(this.updateData, 15000);
};

stopInterval = () => {
    clearInterval(this.intervalID);
};

Thank you very much!


Solution

  • You should not use 'this' in functional components. If you need the intervalID you can save it in a new state.

    MyComponent = () => {
       const [intervalID, setIntervalID] = useState()
        
       const updateData = () => {...}
    
       startInterval = () => {
           const interval = setInterval(updateData, 15000)
           setIntervalID(interval)
       }
        
       stopInterval = () => {
           clearInterval(intervalID)
       }
    }