State in React

State is a React concept that allows us to make our apps more interactive and mutable.

React components has a built-in state object. 

The user interfaces re-renders based on the value of state variables.

Declarative programming: the use of variables such as state to change an object’s property

Imperative programming: explicitly setting an object’s property

Imperative programming is about how a program works while Declarative programming is about what a program does. 

Using regular variables to declaratively change the user interface of a React component will not work. You need a special kind of variable in order to cause React elements to re-render: State variables. You also need special functions called Hooks that look– or hook— into the state of your app to read and modify it.

You use the useState hook in order to get access to the component’s state.

import React from "react";

function App() {
   const state = React.useState();
}

Whatever we put into the parentheses of the useState function is the initial state of the component.

const state = React.useState(123);

If we wanted to access the state variable we just created, we would extract the first element of the state array:

console.log(state[0])
// prints out 123

Whenever you change state, React updates any UI elements corresponding w/ that piece of state automatically.

Using state[0] to access state variables is kind of unintuitive though and not the most efficient way to code. So we can use destructuring to make it easier on us as programmers:

const [count] = useState(123);

console.log(count);
//prints 123

How do we change the value of state variables?

const [count, setCount] = useState(123);

setCount(count - 1);

console.log(count);
// prints 122

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s