ExceptionsManager.js:179 Error: Invalid hook 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
Getting this error in Playbutton component
Playbutton.js
import { useNavigation } from "@react-navigation/native";
import React, { useEffect, useState, useRef } from "react";
import { useSelector, useDispatch } from "react-redux";
import {
View,
Button,
StyleSheet,
Image,
TouchableOpacity,
Dimensions,
NativeModules,
} from "react-native";
var deviceHeight = Dimensions.get("window").height;
var deviceWidth = Dimensions.get("window").width;
import useAppleFunction from "../CustomHooks/useAppleFunction";
const PlayButton = () => {
useEffect(() => {
useAppleFunction();
}, []);
}
and here is the custom hook useApplefunction.js
import { StyleSheet, Text, View } from "react-native";
import React, { useEffect } from "react";
import { useSelector } from "react-redux";
const useAppleFunction = () => {
const Playlist = useSelector((state) => state);
console.log("reduxcheck=",Playlist);
useEffect(() => {
runtimer();
}, []);
const runtimer = () => {
console.log("reduxcheck=1",Playlist);
};
};
export default useAppleFunction;
const styles = StyleSheet.create({});
CodePudding user response:
React's error messages are very informative and some are written passively aggressive to make you feel bad for not reading enough documentation.
The first clue is "Hooks can only be called inside of the body of a function component.", you are calling your custom hook in another hook.
Also, out of the 3 reasons listed, only one seems to match your case and it's #2, you're breaking the rules of react hooks.
So instead of calling your useAppleFunction hook inside useEffect, you should call it at the top level and save the returned value (in your case, nothing) into a variable.
CodePudding user response:
A hook does not need to return anything, thus if useAppleFunction
is supposed to be a hook, then this is fine. However, this should not be called inside a useEffect
.
This is documented here.
To avoid confusion, it’s not supported to call Hooks in other cases: