Hooks in React
Tags: javascript, react, programming, webdev
Published: 2022-07-05 05:18:40

React is a powerful tool for javascript users, it is a library that allows us programmers to create user interfaces much more efficiently than just using vanilla javascript. React gives us a way to create our programs declaratively. `Declarative programming` is determining what you want the end result to be without going step by step. `Imperative programming` is what you would do with plain old javascript going step by step describing how you would like to manipulate the DOM.
```javascript
const button = document.createElement('button');
button.textContent = "Click Me";
const body = document.querySelector('body');
body.appendChild(button);
```
In the above example, the programmer must step by step tell the computer what to do, from creating the button element to finding where it should go and lastly appending it the correct element. With React we can use JSX which is similar to do those same steps quicker.
```javascript
return(
   <button>Click Me<button>
);
```
The JSX shown above is then converted using Babel into something the computer can understand. This quick introduction to React is to get you ready for the real topic, and that is hooks. `Hooks` are special react functions that allow you to essentially "hook" into components' state and lifecycle. There are a multitude of different hooks in React , but the ones we will focus on are the useState and useEffect hook.

#The useState Hook
Probably the most important hook that you can use is the `useState` hook. As was said earlier, hooks are special because they allow you to "hook" into different things. In this case, it will be hooking into the components state. `State` is a special React object that contains information about data regarding a component. Whenever that data is changed, the component will re-render based on the new data.

##How To Use The useState Hook
In order to use the useState, it will need to be imported in the file that you will be using it in, just like you need to import React.
```javascript
import React from "react";
```
The above example shows how to import React, but we need to add another detail to be able to utilize the useState hook.
```javascript
import React, { useState } from "react";
```
With that line of code, we are all ready to begin. Consider the code snippet below:
```javascript
import React from "react";

function MyButton() {
   function handleClick() {
      console.log("On");
   }

   return (
      <div>
         <h2>Click the Button</h2>
         <button onClick={handleClick}>Off</button>
      </div>
   );
}
```
We have a component called `MyButton` that has a button that when you click it, it will print on the console "On". However, what if we want the button text to change between "On" and "Off" based on when the user clicks it. We can do that by implementing the useState hook.
```javascript
import React, { useState } from "react";

function MyButton() {
   const [isOn, setIsOn] = useState(false);

   function handleClick() {
      setIsOn(!isOn);
   }

   return (
      <div>
         <h2>Click the Button</h2>
         <button onClick={handleClick}>
            {isOn ? "On" : "Off"}
         </button>
      </div>
   );
}
```
Some of the code above may look new, the first line of the function is where you initialize state. It may look strange but we declare it with a de-structured array, because when you use the useState hook, it returns two things. First a variable that holds the current state, and second a setter function to change the value of the state. Always use the setter function, do not set it directly with the variable. One of the perks of the setter function, is when it is called and state is changed the component will re-render itself. In the example above the button has a text that changes based on state using conditional rendering. Whenever the button is clicked the text should fluctuate between "On" and "Off", without needing to refresh the page. This is just one of the ways to use the useState hook, it is a very helpful tool that makes your website more responsive and user friendly.

#The useEffect Hook
The `useEffect` hook by default, runs a set of statements every time the component renders. Just like with the useState hook, you need to import it, in order to be able to use it.
```javascript
import React, { useEffect } from "react";
```
There are many different uses for the useEffect. One example could be to set a timer that restarts each time the component re-renders. Take a look below to see an example of the useEffect being used below.
```javascript
useEffect(() => {
   console.log("Component has be rendered");
});
```
This is just a quick example to show the syntax of the useEffect hook. Within the call of the hook is a function that will be run at every component render, as previously stated. However, sometimes you do not want the function to run at every render, but only once or sometimes. This can be accomplished with a dependency array that is put down as the second parameter of the useEffect hook function call.
```javascript
useEffect(() => {
   console.log("Count has been changed");
}, [count]);
```
When there is a variable within the dependency array, the function will run the first time the component renders, as well as each time the value of the variable changes. There can be multiple values in the array. There can also be no values in the dependency array, which would cause the function to run only the first time it is rendered. An important use of an empty dependency array is when you are fetching data from an API, you usually only need to that once initially.

#Conclusion
Hooks are a valuable tool to use when programming in React. Hopefully, you have learned enough and can get to practicing, because remember practice makes perfect.

##Resources
* [React useEffect Hooks](https://www.w3schools.com/react/react_useeffect.asp)
* [ReactJS State: SetState, Props and State Explained](https://www.simplilearn.com/tutorials/reactjs-tutorial/reactjs-state#:~:text=HackerEarthEXPLORE%20COURSE-,What%20Is%20'State'%20in%20ReactJS%3F,%2C%20the%20component%20re%2Drenders.)
* [Using the State Hook](https://reactjs.org/docs/hooks-state.html)