DEV Community

Cover image for React Hooks or Online Classes?
Kanishk gupta
Kanishk gupta

Posted on

React Hooks or Online Classes?

State management:

It's the same thing that every college student does during his online classes. I am seriously not kidding!!!

The state can be understood by a simple example of a switch that has two states 'ON' and 'OFF'
Alt Text

During online classes or any college lecture, we only attend to be either present or absent rest we study on our own.

In react we manage them by defining a state and then keep on updating them according to the scenario.

In the hooks approach, we use "useState" for managing state.

State Hooks:
Let us define a state hook for student:

// State hooks for student

const [student,setStudent] = useState('');

The initial value is an empty string and if we print student then:

console.log(student) // Output will be blank as string is empty.

Now to change the state we need to update the value as:

setStudent('Present")

console.log(student) // Output will be 'Present'

here "student" is used to store state and "setStudent" is state handler that is used to update the state.

The states can be in any form, say numbers, a string, array, or an object depending on the use case and what we want to make.

Alt Text

Effect Hooks:
In React every component has a basic three life cycle approach:

  1. Mounting

  2. Updating

  3. Unmounting

Again, a lecture example whatever be the situation we need to attend and be present similarly "Mounting" works, whenever we start our react app they are mounted and rendered. If we talk about using Hooks that can be done by:

useEffect(
()=>{

//Operation to be performed

},[])

"UseEffect" method without any state variable which mounts the state we want when our app is launched i.e. "joining online classes and be present".

Now updating the state or Update cycle:

If a state exists, then we need to update its value like if we turn a switch on, we need to turn it off.

useEffect(()=>{

//Operation to be performed

},[state])

here, the state refers to the state variable. Whenever its value will be changed the state will update and the operation inside will be performed.

Here's a simple application that is based on Hooks:
Can play with here.

Alt Text

this game we need to find the coordinates of a point inside the square box if that matches Voila!

What I have done is when the user starts or generates the coordinate the time starts and based on the movement the state is updated, as soon as it matches with the generated coordinates the state is set to false and the game ends.

A simple and easy implementation of hooks concepts.

Code can be found here

This was originally written at my personal blog

Top comments (0)