Before the problem, first the condition:
There’s a FullStack JS developer condition, called ‘JavaScript fatigue,’ which refers to the ‘inability to keep up with the latest tools, the fear of becoming obsolete, the constant change of the ecosystem, and the overwhelming choice,’ according to an article written by Kim Maida.
There is no better example of this point than in the way which one handles state in React. There are at least 4 ways to handle state on the front end as of this writing, and depending on the project, any of these solutions may be useful.
However, one method of handling state, class based component state, is used far less at the moment. In this article I’m going to cover the useState
hook, and why it works well when using functional components in React.
What is State? State is a form of memory in an application, most often it can be an object, variable, array, or some other form of data. State is not always needed in an application. A tic-tac-toe game requires a save state. An application tracking a mouse cursor doesn’t require a save state.
Coming from a Game Design background, I was very excited to learn that state was such a crucial part of Full Stack Software Engineering. A state machine remembers things like what level in a game is being rendered, what NPCs are meant to spawn in a particular level, where the treasures are…
Anyway, let’s look at an example of state within a React Class Component:
CLASS COMPONENT STATE
import React from 'react'class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()}; }render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
A lot to parse here.
First we are creating a class named Clock
which inherits the from the component based system in React. Then there is class constructor(props)
which assigns props and calling of super(props)
, which allows us to the this
in within the class component. this
is how we call props
, shorthand for properties.
Class Clock
has state. this.state
declares an date
object, which is built using the Date()
function from the built-in JavaScript library.