Table of contents
Since React is the most popular, free and open-source front-end JavaScript library nowadays, half of us (developers) already know about react and the basic concepts of hook.
For those who are beginners and start with React, React is working on the concept of 'class Component' and 'Functional component'. We are talking about both concepts in depth in another article. For now, let's get started with hooks.
So, Hooks very popular word nowadays for developers, And might seem like a scary one, but trust me it's not, It's one of the easiest things to learn and It's made lots of our job so easy.
Let's learn what is hook first in two ways
1 . Traditional Definition (Boring one ๐ฅฑ)
Hooks are functions that allow you to use state and other React features in functional components, which traditionally have not had access to these features. They allow you to reuse stateful logic between components, and to separate concerns like state management, lifecycle methods, and side effects into separate functions. Some commonly used hooks in React include useState, useEffect, useContext, and useReducer, among others.
2. Throw a funny analogy :
"Hooks are like little helpers that sneak into your components and do all the boring work for you, so you can focus on the fun stuff like making your app look cool and pretending to know what you're doing
You seem still confused, Let me make it easy for you, Just be with me
useState Hook :
Let's Start with this hook, useState is one of the basic and simplest hook in React, Before getting started let's see what is the syntax for the useState hook.
// syntax for useState hook
const [state , setState] = useState();
state
and setState
are both variables returned by the useState
hook.
The `state`
variable is used to store the current value of a piece of state data in a React component. It is similar to a variable declared with let
or const
, but it is special in that it triggers a re-render of the component whenever it is updated.
Where, The setState
variable is a function that is used to update the value of state
. When called with a new value, setState
updates the state value and triggers a re-render of the component to reflect the updated value.
By closely observing the above syntax, It looks like Arrya destructuring.
If you are not familiar with Arrya destructuring, let me give you a small intro.
Array destructuring is a feature in JavaScript that allows you to unpack values from an array or object into separate variables. This can be a convenient way to access and work with individual values in an array without having to access them by their index.
Array Destructuring:
const myArray = [1, 2, 3];
const [first, second, third] = myArray;
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(third); // Output: 3
I hope it helps you.
Coming back to useState
hook, the useState functional hook returns an array with two variables which are state and setState, we can name it according to our convenience. (See how friendly is useState is ๐)
Let's understand the use of useState
with a funny example.
"ASSUME" you have an annoying and at the time carrying partner(Girlfriend/Boyfriend), who can change your mood when you call him/her.
Let's convert this relationship into javascript ๐.
import React, { useState } from 'react';
function MyComponent() {
const [mood, setMood] = useState('happy');
function handleClick() {
setMood(mood === 'happy' ? 'angry' : 'happy');
}
return (
<div>
<p>My mood is {mood}.</p>
<button onClick={handleClick}>Calling .....</button>
</div>
);
}
Here each time you click on a Calling button, It triggers the handleClick function. In handleClick, there is a mood spoiler, the setMood function (Your partner) in a form of a variable which is returned by a useState
hook. (Similar to setState from the above syntax of useState() )
Here setMood("changes your mood vice-versa") updates the state called mood
, According to the condition inside setMood
function.
One thing to notice here is that each time page is refreshed or a component runs for the first time, The initial value of state which is declared here as mood
is "happy
". If we passed an empty bracket, in technical terms if we don't pass any argument inside `useState()` hook then the original or default value of state is undefined .
Apart from the joke, whenever we hit the button it triggers the function which has function 'setMood()' which updates the state of the component to the parameter we passed in the brackets. And as you know nothing is free in this world updating the state produces the 're-render' of the component.
So It is not a good practice to always use hooks to update the state or we can say the entities which are not frequently updated and do not impact much on other functionality of the component
Let's wrap this hook with a small and sweet example :
(PS : It's a traditional example from many blogs which are based on a useState
So as the traditional thing, I also have to let you know about it ,I hope you get all the things from above example .)
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<p>You clicked {count} times.</p>
<button onClick={handleClick}>Click me</button>
</div>
);
}
In the above code, we define a functional component called Example
which uses the useState
hook to manage a state variable called count
. The count
variable is initialized to 0
using the useState
hook. The setCount
function returned from useState
is used to update the value of count
.
We also define a handleClick
function which increments the count
value by 1 each time the button is clicked. This function is called when the button is clicked using the onClick
event handler.
Finally, we render the current count
value and a button to update the count
value when clicked.
Conclusion :
In conclusion, the useState
hook is a built-in React hook that allows us to manage state in functional components. It provides a way to define state variables and their initial values, as well as a function to update the state variables.
Using the useState
hook can make our code more concise and easier to understand, as it allows us to manage state within the component itself instead of having to rely on external state management libraries. It also provides a way to trigger re-renders of the component when the state changes, which can update the UI to reflect the new state.
(PS: I am also a learner so feel free to correct me, if I messed up somewhere. Thanks for reading )