Can I use "let" in react function component?

Viewed 4294

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();
}
2 Answers

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, e.g.

  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

Related