React Hooks — Additional Hooks you need to know and Netlify Deployment

Julie Gunawan
11 min readMar 12, 2022

Hi again! Last time, I left with topic on intro about React and React hooks, specifically useState. This time, I want to continue our learning path with React Hooks in more detail. At the end, I also will show you how to deploy our React project to Netlify. Excited to start? Let’s not waste time.

Previously, we created buttons/checkboxes that can change the value of a variable when those buttons/checkboxes are clicked. Now, we will create a combination of button and checkbox, and integrate useEffect hook on them. UseEffect allows you to perform side effects and function components (as how Eve Porcello described). Example of side effects are: fetching data, DOM updates directly, and times. In order to use useEffect, we need to import them from React library. In short, the way this useEffect works is that every time we change the state, useEffect is fired. The example below uses useEffect to change the web page title. On top of that, the function will print some value when there is an event triggered.

Create button and checkbox that can trigger an event when integrated with useEffect

If you want to understand the dependency array better, when using useEffect, check out this code below. What the code does is that it consoles the value entered, when there is an event changed. See how val vs val2 printed in the console log, depending on which box is filled. This happens because we specify which variable to be shown, through dependency array.

I will give more example about dependency array in the next section.

FETCH DATA WITH useEffect

In this scenario, we want to use online API data that already exists: GitHub API (https://api.github.com/users), and we want to list all the username in the API. How can we do that? This is where useEffect comes into play.

Fetching API data using useEffect

It is recommended to use dependency array when you are fetching data. By combining the hook with dependency array, we are telling React to call the API only once: when the component first render, otherwise we will get extra HTTP request over and over again. Remember how dependency array was previously used to better control which variable to display when there is a triggered event? But, in this case, we don’t have to pass the name of the variable, since we are fetching the whole array. To better illustrate the importance of dependency array in useEffect, let’s add a button to clear the list that is printed by the called function.

When you click the button, the list is cleared up; works like how we expect. Let’s delete the dependency array and run the code again

You will see that without dependency array, the list <li> is generated over and over again (like an infinite loop). By adding dependency array, we tell React to just call the fetch once, so when delete button is clicked, there is no more call to the fetch. If you are confused on how to use dependency array, check out this blog.

We could also pass an argument to the function App. For example, we want to specify a particular user information to show. The code below will make our wish happens.

ANOTHER DIFFERENT TYPE OF HOOKS — useReducer

What is useReducer? and how is it different from useState? The useReducer hook is similar to useState, but it allows for custom state logic. In the other word, useReducer is needed if we have a more structured approach for updating multiple values of our states independently. This useReducer takes two arguments, with optional of third argument: reducer (a JavaScript function), initialState, and initializer (for more detail, read this blog). The way you would write useReducer will be this way: useReducer ( () => someFunction , 0). For example, we have a number; using useReducer, we want to add this number (initial state) with another number (number passed through setNumber function), when the number is clicked. The code below will increment the number by 2, with initial value of 5:

REFACTORING useState TO useReducer

There is a way to minimize or shorten the code (in case you freak out when looking at how long your code is). Using previous example, we can replace setChecked on the onChange event, to useReducer, like code below.

Instead of using setChecked, we replace the function to toggle, and we define the function to change checked status to unchecked. Voila, now we have a cleaner code.

We can also combine useReducer in different scenarios using switch case. The code below uses function reducer, that takes 2 arguments (state and action). Using action.type for the condition, we can set what value it will return. We also could define an object with 2 different attributes, and change the value based on the input selection.

The use of useReducer to dispatch action

I also want to touch the difference between double quote, single quote, and backtick in JavaScript. Eve Porcello’s video showed us how to access the previous state of the string variable using backtick. This blog gives example on how useful is backtick in string concatenation. Pay attention to the code below line 14, 18, and 50, to see the effect of backtick and accessing the previous value stored in the variable.

NEXT TYPE OF HOOKS — useRef

Okay, so far we only have buttons and dropdown options in example. Let’s create a form that will take in some inputs. To manage the value of those inputs, we need to import useRef from React library.

How to utilize useRef in form element

To reset the value of both label and color, we need to assign the label.current.value and color.current.value to empty string (“”).

We need the preventDefault() function due to the default behavior of the event when submitting form: reload the browser. To understand preventDefault() function, check out this blog.

CONTROLLED COMPONENTS to HANDLE FORM in useState

Let’s go back to useState, and delete the useRef, to handle our form. Why do we wanna do that? Apparently, useRef stores value in current property, where you can view them (when value is updated) in console, but not in browser. Check out this example. Because users interact with browser, clearly, we need to display any updated/changed value of the form right on the browser; to do this, we need to use useState. Let’s revise our code.

CREATE CUSTOM HOOKS

Now that we created a hook to take in a form input, we want to be able to reuse them in different part in React. Let’s try to split the App function and move all these hooks to a file named useInput.js; this useInput.js is the file we want to export the file so we can reuse the functionality of hooks we created. It is important to remember that Hooks have to start with the word “use”. Check out the Rules of Hooks here. First step to do is create a new file called useInput.js under src folder. This useInput hook will return an array.

Create useInput.js file to create custom hooks

Then, we start transferring the code from App function to this file, like code below. Don’t forget to import useState from React library, then export this file.

How useInput hook looks like

And this is how you would want to write your input.js

How to use useInput in index.js

You see how I use <input {…label}> to replace “value={label}”? The three dots is part of JSX expression, called Spread syntax. It is very useful especially when you are trying to do iteration (in an array or JSON object, for example), where there is zero or more arguments are expected. How it works is that it will spread out the value of properties and assign it to different variable.

To be more clear, let’s create an example, using array:
var arr1 = [1,2,3,4];
var arr2 = [4,5,6,7,8,9];

Then, you want to combine the above arrays into an array. You can do it this way: var arr3 = […arr1, …arr2];

Similarly with an object, let’s say you have a key-value pair object, and you want to pass that object into a component, you can write it as …nameOfTheObject. Read more in this guideline. The JSX expression is used in our code because, as I mentioned earlier, useInput returns an array, but we don’t know how long is the array, and in order to make sure we capture all the value, we need to utilize these three dots.

useContext TO TRANSFER ALL DATA (with its descendants)

What is Context in React? It is a data transfer method between component trees (parent-child relationship). Context is mainly used when data needs to be accessible by different components at different levels. Read more about context in this link. Now, how do we useContext to transfer data? How can we use them with hooks? First, you need to import createContext from react library. Then create an exported variable to initialize createContext(). On top of that, you have to have another variable that actually contains the data you need to transfer. We will put App function into App.js file, and keep the rest in index.js Scroll down and check the code below to better understand.

App.js (left) and index.js (right) that is consoling the result object

Provider in context is going to provide the data to App component and everything below it. You need to pass the value of your data into the bracket <>; in my case, I have myValue variable that I want to pass down (or use in different files), thus I have <MyContext.Provider value ={{ myValue }}>. Besides, we can see that App.js is just printing the value of useContext(myContext), which is stored in result. We can see how result variable contains an object that has similar value to myValue variable in index.js. Now let’s destructure the object, and print them in a bullet list, in browser.

Destructuring object when used in different file

Let’s examine the App.js code on the right; because we pass { myValue } to the Provider in index.js, we need to use the same name of { myValue } in App.js. Go back to my previous blog to re-learn about object destructuring.

USE CUSTOM HOOK with CONTEXT

We had an example where useContext can be used to transfer an object, and its descendants, from one file to another file, to be useable for components. We can also create a custom hook with content in it, to make it simpler. Instead of exporting createContext(), in index.js, we will export our custom hook: which in the code below, I call my custom hook useFruits, combined with MyContext. Additionally, we don’t want to import MyContext anymore, instead, we will import our custom hook.

App.js on the left and index.js on the right, using useFruits as the custom hooks

FETCH DATA using CUSTOM HOOK

There are three different scenarios that needs to be considered if we want to fetch data using our custom hook:
1. When there is a data data is not available yet
2. When data is not available yet, but it is loading
3. Lastly, when we there is an error

Similar to our useInput custom hook, we need to create a new file, and let’s call it useFetch that takes in a url (to an API). As I mentioned the three conditions above, we need to create 3 constants and set the initial value, in the beginning of the code; then, use useEffect to fetch data.

index.js on the left and useFetch.js on the right

Remember, we can change the value passed to App with any name you want, as long as they are available in the github API. You can also use different API. We can also choose to display any information, based on the key-value pair of JSON from the API. To learn more about custom hooks, check out this article.

DEPLOYMENT WITH NETLIFY

In order to deploy your React application, you need to ensure that react-scripts build is available in your package.json file. This is how it looks

Build scripts in package.json

What this scripts does is that it will create a production build for the current project, when you run “npm run build”. Production build is a minified, bundled up project package that you can send to the hosting providers. You can also test this with other hosting providers, such as: Heroku, Firebase, AWS, and so on.

Once you run the command above, check on the build folder and make sure if the production build is created.

Build folder for deployment

After that, serve it up with static server, by installing serve package with this command: “npm install -g serve”. Serve will give a static server that you can use on your computer. Next, you need to serve the build folder to localhost:3000, or the network.

Static server created by serve package

Next, make sure you have an account with Netlify. If you don’t, you can sign up with one of the options provided, for free. The good thing about Netlify is that you can just drag the entire build folder and drop them to the box provided, if you wish, instead of using Git. You also have the option to use Git to deploy your project.

Netlify deployment options

As soon as you deploy it, Netlify will generate a link you can use

Now that we have learnt how to deploy it to the web, let’s try to create a proper full stack project next. Follow my next journey to learn more. Have fun learning!

--

--