React state={}

what is state ?

starting with the dictionary, it indicates that state means “the particular condition that someone or something is in at a specific time.” The developers at facebook define react as “The state starts with a default value when a Component mounts and then suffers from mutations in time (mostly generated from user events). It’s a serializable* representation of one point in time — a snapshot.” Lastly from my understand state is when the State of a component is an object that holds some information that may change over the lifetime of the component.

Examples 👇🏾

Above we have set our state object to a key named “clicked” and we set the value of it false. Here come my favorite part! when we want to change our state we have used this built in method called this.setState(). When a value in the state object changes, the component will re-render, meaning that the output will change according to the new value or values. So here in our code we out we wrote function that handles our state changing and if you look inside of the function we have *drumroll* “this.setState()”

What our function is trying to do here is when a certain event occurs, state change state to the opposite of what it is at the moment, but for that to happen the user has to trigger our clickHandler function and that would trigger our this.setState method.

So in order for our for our code do what we want it to do we have pass in an eventListener and here we will be using “onClick”. So here in our button tag, we pass in the function we wrote to our event. Every time the user clicks on the button it triggers the function and switches our state from true to false depending on the click. What’s below how button is a conditional (ternary) operator and what it is doing is that if your state.clicked is true? display an h2 tag. If our state.clicked is equalled to false display null which means empty.

Here in our app we can see that there is a button but it is not clicked which also indicates here that our state is set to false and there is not h2 tag with our “bark” displayed. However once we click that is when the magic happens.

So what is happen here is that once the user click on the “Bark” button it changes our state and every time our state changes it re-renders our whole application. When the user clicks the button again it switches it back emptiness and our bark doesn’t show.

P.S what a cute dog 😍 🐶

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store