in this case, it will trigger render again when I call updateNumber(), so how can create the valuable that it is for saving data only?
function test() {
const [cartNum, setCartNum] = useState(0);
function updateNumber() {
setCartNum(number 1);
}
return (
<View style={{ flex: 1 }}>
<TouchableOpacity onPress={updateNumber}>
<Text>
{Math.random()}
</Text>
</TouchableOpacity>
</View>
);
}
CodePudding user response:
Use the useRef
hook
Example below
// Call on top of component
const number = useRef(0);
const updateNumber = ()=>{
number.current ;
}
CodePudding user response:
There are 2 ways for it to update and not re render:
// by using normal variables
function test() {
let number = 0;
function updateNumber() {
number
}
return (
<View style={{ flex: 1 }}>
<TouchableOpacity onPress={updateNumber}>
<Text>
{Math.random()}
</Text>
</TouchableOpacity>
</View>
);
}
// or as carlos mentioned by using ref
function test() {
const number = useRef(0);
function updateNumber() {
number.current ;
}
return (
<View style={{ flex: 1 }}>
<TouchableOpacity onPress={updateNumber}>
<Text>
{Math.random()}
</Text>
</TouchableOpacity>
</View>
);
}
Hope it helps. feel free for doubts