I was creating a custom hook in react native and encountered a problem with useEffect and useState, resulting in an infinite loop.
I created a little snack to exemplify what is happening:
import React, { useEffect, useState, useMemo } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
export default function App() {
const [testStateVariable, setTestStateVariable] = useState(false);
const useCustomHookTest = () => {
let testVar = ""; // Change the value "" to [] to see the problem;
return useMemo(
() => ({
testVar,
}),
[testVar],
);
};
var { testVar } = useCustomHookTest();
useEffect(() => {
console.log("CHANGE OF testVar!")
}, [testVar]);
return (
<View style={styles.container}>
<Button title="Change a state to true" onPress={() => {setTestStateVariable(true)}}/>
<Button title="Change a state to false" onPress={() => {setTestStateVariable(false)}}/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
});
Basically, when I use an array inside a custom hook, it re-renders and changes the value of the variable every time any state changes. You can see this changing the value of testVar to [] and press the two buttons to change the states, the useEffect is fired at every state change, but this doesn't happen when the value is "".
I tried using useMemo but it didn't work,
Does someone have a solution for this problem?
Thanks