Home > Back-end >  execute hooks inside a function in react native
execute hooks inside a function in react native

Time:08-30

Can I use hooks inside a function? For example I have implemented the following code:

import React, { useState, useEffect, Component} from 'react';

export default class  App extends Component {
   checkdata_db(){ 
      const [booblenavalue,setboolenavalue]=useState(false); 
              useEffect(() => {             
              setboolenavalue(true)
            }, [])
            console.log(booblenavalue);         
   }
    render(){
    }
}

This code doesn't work. It throws the following error:

Invalid hooks call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app" How can i run hooks inside checkdata_db method?

CodePudding user response:

Hey @Elly as @yousoumar said , you cant use hooks in classes , it can be only done with functional comp:

You can convert it to like this :

Also you cant use useEffect,useState inside any conditional statements like if,else etc.

So you need to add useEffect outside any functions etc

import React, { useState, useEffect, Component} from 'react';

const   App = () =>  {
const [booblenavalue,setboolenavalue]=useState(false);
  useEffect(() => {             
              setboolenavalue(true)
            }, [])
   const checkdata_db = () => { 
       
            
            console.log(booblenavalue);         
   }
    return <View />
}

Hope it helps feel free for doubts

  • Related