简体   繁体   中英

Can I use “let” in react function component?

I am studying React currently.

Can I use "let" in function component 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();
}

That's not a functional component, as a functional component has to return a React Element.

If it would be a functional component, 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 , eg

  setTimeout(changeFruit, 1000);

then the component won't rerender after the variable changed. That's not what you want usually. If you useState and call the setFruit function, the component rerenders.

Can I use "let" in function component instead of using "useState"?

The answer is No, you can't use let instead of state. Your component 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM