I am studying React currently.
Can I use "let" in function ponent instead of using "useState" ?
const Func = () => {
let fruit = "banana";
const changeFruit = () => {
fruit = "apple"
};
changeFruit();
}
const Func = () => {
const [fruit, setFruit] = useState("banana");
const changeFruit = () => {
setFruit("apple");
};
changeFruit();
}
I am studying React currently.
Can I use "let" in function ponent instead of using "useState" ?
const Func = () => {
let fruit = "banana";
const changeFruit = () => {
fruit = "apple"
};
changeFruit();
}
const Func = () => {
const [fruit, setFruit] = useState("banana");
const changeFruit = () => {
setFruit("apple");
};
changeFruit();
}
Share
asked Oct 24, 2019 at 15:41
Tsubasa YamaguchiTsubasa Yamaguchi
1751 gold badge3 silver badges11 bronze badges
2
-
4
In a word, no. Your ponent won't rerender when the let value changes. Calling the set function returned by
useState
is how React knows to rerender the functional ponent. – Jared Smith Commented Oct 24, 2019 at 15:42 -
1
let
has nothing to do withuseState
. Your question is about the impact of removinguseState
and nothing to do with let. – Ayush Gupta Commented Oct 24, 2019 at 15:46
2 Answers
Reset to default 7That's not a functional ponent, as a functional ponent has to return a React Element.
If it would be a functional ponent, and you change the variable synchronously before returning the Element, it's fine:
const Func = () => {
let fruit = "banana";
const changeFruit = () => {
fruit = "apple"
};
changeFruit();
return <>{fruit}</>; // displays "apple"
};
If you change it asynchronously, e.g.
setTimeout(changeFruit, 1000);
then the ponent won't rerender after the variable changed. That's not what you want usually. If you useState
and call the setFruit
function, the ponent rerenders.
Can I use "let" in function ponent instead of using "useState" ?
The answer is No, you can't use let instead of state. Your ponent won't re-render, that's what state is all about
Please consider React docs to help you understand the concept of state in React
Hope it helps