Learn Advanced React_ Advanced React_ Custom Hooks Cheatsheet _ Codecademy
Learn Advanced React_ Advanced React_ Custom Hooks Cheatsheet _ Codecademy
The useEffect hook performs side effects every import React, { useState, useEffect } from
time a component renders. useEffect accepts two
'react';
arguments in the form of useEffect(callback,
dependencies) . The callback argument holds the
side-effect logic and is executed every time a render function TitleCount() {
happens. const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count}
times`;
}, [count]);
There are two main rules to keep in mind when using // Instead of confusing React with code
hooks:
like this:
1. Only call hooks from React function components.
2. Only call hooks at the top level, to be sure that if (userName !== '') {
hooks are called in the same order each time a useEffect(() => {
component renders.
localStorage.setItem('savedUserName',
Common mistakes to avoid are calling hooks inside of userName);
loops, conditions, or nested functions. });
}
Effect hooks
Effect hooks are useful for performing “side effects” useEffect(() => {
after render such as fetching data and reacting to state
fetch("https://some-api.com/get-some-
changes.
user-information")
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
});
}, [])
Effect Dependency Array
useEffect(() => {
alert('called when value of `endpoint` or
`id` changes');
}, [endpoint, id]);
Custom Hooks
Custom Hooks are JavaScript functions that make use of const useTheme = () => {
other hooks, follow the rules of hooks, and whose names
// "theme" state with a default value
begin with use . Custom hooks are simply a convention
and the programmer can decide what they do and what of "light".
they return. const [theme, setTheme] =
The provided example is from the Playing Hooky project.
useState("light");
This custom hook changes the page’s appearance to
“dark” or “light” mode while providing the current // Changes the pages CSS styling.
theme value for use elsewhere in the application. useEffect(() => {
document.documentElement.setAttribute("dat
a-theme", theme);
}, [theme]);
// Function executed in the application.
const onToggleTheme = () => {
setTheme((previousTheme) =>
previousTheme === "light" ? "dark" :
"light");
};
// Makes the function available for use
in the application.
return {theme, onToggleTheme};
}