4Geeks logo
About us

Learning library

For all the self-taught geeks out there, here is our content library with most of the learning materials we have produced throughout the years.

It makes sense to start learning by reading and watching videos about fundamentals and how things work.

Data Science and Machine Learning - 16 wks

Full-Stack Software Developer - 16w

Search from all Lessons

Social & live learning

The most efficient way to learn: Join a cohort with classmates just like you, live streams, impromptu coding sessions, live tutorials with real experts, and stay motivated.

← Back to Lessons
Edit on Github

React Hooks Explained

Why hooks?

Why hooks?

Functional components passing props are amazing because they are simple, perform fast, and require little code, but they can lead to the much dreaded "wrapper hell" in the quest for maintaining encapsulated components. On the other hand, class components are often confusing to work with for both humans and machines, they often lack a positive developer experience, which makes it more difficult to create a more positive user experience as well. Hooks provide a way for us to use state and lifecycle methods with minimal code, like giving your components superpowers!

Do my components need superpowers?

In general, using props is enough to create an amazing component, but sometimes you need more. Here are some really useful examples to know when to use hooks:

  1. If you want to open or close a modal or dialog- use the useState hook.
  2. If you want to fetch some data only at the beginning of the program execution, use the useEffect hook.
  3. If you want to share information within all components, use the useContext hook. We will talk more about the useContext hook in a separate lesson.

Through experience, you will learn when to use a hook. If you don't think you need them, DON'T use them! The less the better.

Most applications need at least one useState and one useEffect. To make use of hooks, we MUST FIRST IMPORT them at the beginning of our file. For example, if we need useState, we would do:

1import React, { useState } from 'react';

And if we want to use useEffect as well, we can include this:

1import React, { useState, useEffect } from 'react';

Now let's learn how to use them :)

The useState hook:

The most important hook, is almost unavoidable! The useState helps you initialize a variable and change its value over time without the need for parent components. This is how you can use it:

1// variable name setter name initial value (any value) 2const [ mySuperVariable, mySuperFunction ] = useState( null );

Basically mySuperVariable will be initialized with null, and then you will be able to re-set its value by calling mySuperFunction like this:

1// here we are re-setting the value of mySuperVariable = 'hello' when the user clicks on a button: 2<button onClick={() => mySuperFunction('hello')}></button>

Possible uses for the useState hook

  1. Counting: Displaying the number of likes on the screen and being able to increase or decrease when the user clicks. React Counter with Hooks Edit Simple counter using useState and react hooks
1import React, { useState } from "react"; 2import ReactDOM from "react-dom"; 3import "./styles.css"; 4 5const Counter = () => { 6 // initilize a count variable at 0, the setCount function 7 // will be used to re-set the "count" value. 8 const [count, setCount] = useState(0); 9 return ( 10 <div> 11 <h2>{count} likes</h2> 12 {/* Reset count to its previous value + 1 */} 13 <span onClick={() => setCount(count + 1)}>👍🏽</span> 14 {/* Reset count to its previous value - 1 */} 15 <span onClick={() => setCount(count - 1)}>👎🏽</span> 16 <h3>Like or dislike to increase/decrease</h3> 17 </div> 18 ); 19}; 20 21ReactDOM.render(<Counter />, document.getElementById("root"));
  1. Timer/Clock: You can use the system time to show the current time on the screen, but since time changes all the time, we store it with a state variable.

    Building a timer with react hooks Edit React js Clock

1import React, { useEffect, useState } from "react"; 2 3 4const Clock = (props) => { 5 const [time, setTime] = useState(new Date().toLocaleTimeString()); 6 7 useEffect(() => { 8 const interval = setInterval(() => { 9 setTime(new Date().toLocaleTimeString()); 10 }, 1000); 11 return () => clearInterval(interval); 12 }, []); 13 14 15 return ( 16 <div> 17 <h1>{time}</h1> 18 </div> 19 ); 20}; 21 22Clock.propTypes = {}; 23 24export default Clock;
  1. Showing an input on the screen: The best practice to get the content from any input is by storing it on a state variable, this is called "Controlled Input".

    Controlled input field Edit controlledinput

1import React, { useEffect, useState } from "react"; 2 3const ControlledInputForm = (props) => { 4 // holds the value of the input 5 const [currentValue, setValue] = useState(""); 6 return ( 7 <div> 8 <h2>Your name is: {currentValue ? currentValue : "Not defined"}</h2> 9 10 {/* 11 This is a controlled input because its value is in sync 12 with the stated variable currentValue 13 */} 14 <input 15 type="text" 16 onChange={(e) => setValue(e.target.value)} 17 value={currentValue} 18 placeholder="Please type your name" 19 /> 20 </div> 21 ); 22}; 23ControlledInputForm.propTypes = {}; 24export default ControlledInputForm; 25
  1. Opening/Closing (show/hide): A typical use case is having a dialog that asks a question or allows a user to sign up for a newsletter.

Modal Window using react hooks Edit Modal window component with hooks.

1import React, { useState } from "react"; 2import ReactDOM from "react-dom"; 3import "./styles.css"; 4 5const Modal = () => { 6 /** 7 * Using the useState hook, you have to pay attention to 3 elements: 8 * - opened: a variable that will change over time (can have any name) 9 * - setOpened: a function that resets the value of opened (can by any name) 10 * - useState: this is the hook, it has to be setState and it receives the initial value for "opened" 11 */ 12 const [opened, setOpened] = useState(true); 13 14 // if opened === true, I show the modal, else I show the button to open the modal 15 return opened ? ( 16 <div> 17 <h1>Hello BreatheCode</h1> 18 <button type="button" onClick={() => setOpened(false)}> 19 Close 20 </button> 21 </div> 22 ) : ( 23 <button type="button" onClick={() => setOpened(true)}> 24 Open 25 </button> 26 ); 27}; 28 29ReactDOM.render(<Modal />, document.getElementById("root")); 30
  1. Thousands of other possible applications.

Let's explain this hook with a small Modal window example. Here is the live code:

To implement a "Modal Window" we decided to create a hooked variable called opened that is true if the modal window has to be shown to the user.

If the user clicks on "close", we simply use the hook function setOpened to change the value of opened to false.

The useEffect hook:

useEffect hook for the component lifecycle

useEffect is another amazing hook that you will use if you want to execute some code after the component renders, for example:

1) After the component renders for the first time (like the good old componentDidMount).

1const MyComponent = () => { 2 useEffect(() => 3 4 // whatever you code here will execute only after the first time the component renders 5 6 , []);// <------ PLEASE NOTICE THE EMPTY ARRAY 7 8 9 return <Some HTML>; 10}

☝️ Please notice the [] as the second parameter of the useEffect.

2) Every time (or sometimes) after the component re-renders.

1const MyComponent = () => { 2 useEffect(() => 3 // this will run every time the component re-renders 4 if(some_condition){ 5 //this will run only if some_condition is true 6 } 7 );// <------ PLEASE NOTICE THE EMPTY ARRAY IS GONE! 8 9 return <Some HTML>; 10}

☝️ This useEffect does not have an empty array [] as second parameter.

3) When the component will unmount or stop being rendered (like the good old componentWillUnmount function used by class components).

1const MyComponent = () => { 2 useEffect(() => 3 // this will run only the first time the component renders. 4 return () => { 5 // this will run only right before the component unmounts 6 } 7 ,[]);// <------ PLEASE NOTICE THE EMPTY ARRAY 8 9 return <Some HTML>; 10}

Building a Todo List Using just useState and useEffect Hooks

For example, let's say I'm building a todo list, and I have to load the list of tasks from an API. I will have to fetch the information right after the component renders for the first time:

1const Todos = (props) => { 2 // initialize the tasks variable to an empty array and hook it to setTasks function 3 const [ tasks, setTasks] = useState([]); 4 5 // this function useEffect will run only one time, when the component is finally loaded the first time. 6 useEffect(() => 7 // here I fetch my todos from the API 8 fetch('https://assets.breatheco.de/apis/fake/todos/user/alesanchezr') 9 .then(r => r.json()) 10 .then(data => setTasks(data)) // here it re-set the variable tasks with the incoming data 11 , []); 12 13 return <ul>{tasks.map(t => <li>{t.label}</li>)}</ul>; 14}

☝️ Review the code in depth and live demo by clicking here

Further Reading

For more information, including how to build your own hooks, check out: Official React Documentation