How is the use of React Js, state  and useState?

How is the use of React Js, state and useState?

Umut Cakmak
·Oct 12, 2021·

Subscribe to my newsletter and never miss my upcoming articles

The state is specific to the component they are in and is controlled only by the component.

We can say that it is a javascript object that holds all the data that has the potential to change on state components. When the state value changes, the component is rendered and printed on the screen.

How to define states ?

What you see in the code example below is an older usage defined in the class component.

  • State access defined in class components is provided with "this" keyword.

  • In class components, the state is defined in the object.

Class Component state.png

How to define useState ?

  • Basically useState is defined like this

useState.png

  • You can define the useState hook start value. For example ;
const [counter, setCounter] = useState(0);
const [user, setUser] = useState([]);
or
const [user, setUser] = useState('');
const [loading, setLoading] = useState(false);
  • Multiple states can be defined in function components.

  • The state value is updated with setState and returns the last updated value.

  • When the button is clicked below, we increase the setCounter by +1 and show the current value on the screen with the counter.

useState-example.png

Thanks for reading.