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!
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:
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.
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 :)
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>
useState
hook1import 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"));
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.
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;
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".
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
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
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
.
useEffect
hook:useEffect is another amazing hook that you will use if you want to execute some code after the component renders, for example:
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.
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.
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}
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
For more information, including how to build your own hooks, check out: Official React Documentation