What is state?

Music Meier
3 min readDec 17, 2020

--

In React land, state is the data that can be mutated inside of a component. Now, what does this mean? State can be initiated in many different forms. Some common types include, a boolean, an integer, an empty array, and an empty object. There are functional components and class components. For today’s example, state will be demonstrated through the use of functional components and the first state will be initiated with a boolean.

The first parameter inside the array is the state, the second is a function.

In order to change the data, the state must be set. State can be triggered in many ways. Imagine entering a new web page. The creator could have set a counter, and based on a conditional statement, the number on the counter, the click of a mouse, or even the hover of the mouse, the state could change.

The image above utilizes a few different states. The first state is set off by a click function. When a card, let’s call this card a note, is clicked, the function setFlipped is triggered and changes the state of flipped to the opposite of it’s initial state. Let’s introduce two new states, stack and matched.

Stack is initialized as an empty array and will be used to store the cards, “notes.” If a note is clicked, the function, setStack will add a note object to it’s array. When the state of stack changes, meaning an object has been added or removed from the array, a useEffect function will change state of flipped to true using the function setFlipped.

For this particular game, a conditional has be created to ensure once the length of the stack is at 2, the names of the notes are compared to see if they match, if they do, setMatched is used to store the the matched notes that previously resided in the stack. One last state is needed to complete this disappearing act.

For my last trick, I would like to make the matches disappear. The state, isMatched, is initialized as false. And, my lovely assistant, setIsMatched, will be triggered by the state of matched in a useEffect. When, the new notes get added to the state of matched, that means the state has been updated. When that is the case, the specific useEffect that depends on the state of matched will fire off the functions inside, like so:

Inside of the setTimeout function, setIsMatched changes the state of isMatched to true. Then, in the magical world of CSS, there is a ternary stating, that if isMatched is true, change the opacity of the specific cards to 0. And voila, there you have it, state in a nutshell. In it’s simplest form, state is data that can be manipulated. And the manipulation of data can cause a chain reaction setting off many more useEffects that manipulate the data of multiple states.

--

--

Music Meier

Full stack developer with a Masters in Classical Piano Performance and an affinity for travel, learning, and creating.