State In React Js.

State In React Js.

ยท

2 min read

What is a State?

State is simply data that a component can hold over time, necessary for information that it needs to remember throughout the app's lifecycle.

  • It can also be seen as a components memory.

NOTE When updating the components state, it triggers React to re-render the component

Two major things state allows deevelopers to do ๐Ÿ‘จโ€๐Ÿ’ป๐Ÿง‘โ€๐Ÿ’ป

  1. To update the component's view by re-rendering it.
  2. To persist local variables between renders.

How to create a state variable with useState().

In order to use state in practice in a component, we must do it in three steps:

  1. Add a useState() variable
  2. Use it in the code, usually in JSX
  3. Update the piece of state in some event handler

Let's see this in action โœด๏ธ

  • Adding a useState variable

useState variable

  • Using it in the code

useState variable usage

  • Updating the piece of state in some event handler Firstly, create a function that will carry out the update

function for updating useState

Now to use it, we simply write the code below

useState variable usage

NOTE The useState function is what we call a hook in React and we can identify hooks in React by the word "use" before the name of the hook. Also we are not to update state variable manually like the code below

bad practice for useState updating However, we are to always use the setCount method as in this example, outside this, React won't know that the state is updated and as a result, the supposed resulting UI doesn't change.

ย