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:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- 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