最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I use "let" in react function component? - Stack Overflow

programmeradmin0浏览0评论

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 with useState. Your question is about the impact of removing useState and nothing to do with let. – Ayush Gupta Commented Oct 24, 2019 at 15:46
Add a ment  | 

2 Answers 2

Reset to default 7

That'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

发布评论

评论列表(0)

  1. 暂无评论