What is useState hook in React? How to use useState hook?

In react, useState is a Hook and it allows us to have stateful variables in functional components. If we pass the initial value to useState then it returns a variable with the current state value and another function to update this value.

To generate a state associated with the component we usually call useState from the functional component. useState is useful for local component state. Unlike class component, the state can be any type. Each piece of state holds a single value, which can be an object, an array, a boolean, or any other type.

How to call useState?

useState returns an array. The first element of that array is the state variable. The second element is a function to update the value of that variable.

const Order = () => {
  const [data, setData] = useState("Order data");

  return (
    <p>
      {data}
    </p>
  );
};

The useState returns the array like below. But we use array destructuring to make it simple.

const Order = () => {
   const orderData = useState("Order data");
   const data = orderData[0]; // Contains "Order data"
   const setData = orderData[1]; // Contains a function to update state
}