What are React Hooks
React Hooks are functions that give us abilities that we normally don't have in vanilla JavaScript. They all start with the word 'use' and help us avoid writing functions that would've been repetitive. On top of using the built in React Hooks, we can also build our own custom hooks to keep our code dry (not repetitive).
Hooks need to be imported at the top of a react component and only work if they are being called at the top level of a react component. Calling them in other functions or return values would give us errors.
In this blog, we will be covering the following react hooks.
- useState
- useEffect
- useRef
useState
useState
is a React Hook used to handle reactive data. It re-renders the UI when a state of the data changes so that the user can see the changed data.
In the example below, we are using useState
to set the initial value of the count
variable to 0. We are then using state to keep track of count
and update the UI based on a click event that increments the count
variable.
import React, { useState } from 'react'; //import useState
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useEffect
useEffect
is a React Hook used to handle reactive data after UI re-render. We pass it a function (an effect) that needs to happen as a side-effect of a re-rendering.
In the example below, we are using useState
to set the initial value of the images
variable to an empty array. We the use useEffect
to fetch data from an API and setImages
with the fetched data. Then the return value of the function renders the fetched images on the UI.
useEffect
by default re-renders UI every time a component re-renders. This can sometimes cause an infinite loop and could be something we don't want to happen. If we want the 'side effect' to only run the first time our component renders, then we can pass useEffect a second argument of an empty array as shown below.
import React, { useState, useEffect } from "react";
function DogPics() {
const [images, setImages] = useState([]);
useEffect(() => {
fetch("https://dog.ceo/api/breeds/image/random/3")
.then((r) => r.json())
.then((data) => setImages(data.message));
}, []); // second argument is an empty array
return (
<div>
{images.map((image) => (
<img src={image} key={image} />
))}
</div>
);
}
useRef
Just like useState
and useEffect
, we need to first import useRef
to a component in order to be able to use it.
useRef
is a React Hook used to capture a 'reference' to values that are accessible across multiple renders of a component. It returns a mutable ref
object whose .current
property is initialized to the passed argument. In the example below, the .current
value of the count
variable is set to 0.
Calling useRef
creates a new internal .current
value in React and gives us access to that value in a ref variable. To update the value of the ref
in React's internals, we are updating its current property to increment by 1 on a click event using count.current = count.current + 1
.
import React, { useRef } from "react"; // import useRef
function CounterRef() {
const count = useRef(0); // passing it an initial value of 0
function handleClick() {
count.current = count.current + 1;
console.log(count.current);
}
return (
<div>
<h1>CounterRef</h1>
<button onClick={handleClick}>{count.current}</button>
</div>
);
}
Top comments (0)