Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Learn Advanced React_ Advanced React_ Custom Hooks Cheatsheet _ Codecademy

The document provides an overview of advanced React concepts, focusing on the useEffect hook for managing side effects in components. It outlines the rules for using hooks, common mistakes to avoid, and the significance of the effect dependency array. Additionally, it explains custom hooks, their benefits, and how they can be used to abstract and reuse stateful logic across components.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Learn Advanced React_ Advanced React_ Custom Hooks Cheatsheet _ Codecademy

The document provides an overview of advanced React concepts, focusing on the useEffect hook for managing side effects in components. It outlines the rules for using hooks, common mistakes to avoid, and the significance of the effect dependency array. Additionally, it explains custom hooks, their benefits, and how they can be used to abstract and reuse stateful logic across components.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Cheatsheets / Learn Advanced React

Advanced React: Custom Hooks

The Effect Hook

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]);

return <button onClick={(prev) =>


setCount(prev + 1)}>+</button>;
}
Rules for Using Hooks

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. });
}

// We can accomplish the same goal, while


consistently calling our hook every time:
useEffect(() => {
if (userName !== '') {
localStorage.setItem('savedUserName',
userName);
}
});

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

The dependency array is used to tell the useEffect(() => {


useEffect() method when to call the effect.
alert('called after every render');
By default, with no dependency array provided,
the effect is called after every render. });
An empty dependency array signals that the effect
never needs to be re-run.
useEffect(() => {
A non-empty dependency array signals that the
hook runs the effect only when any of the alert('called after first render');
dependency array values changes. }, []);

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};
}

Use of Custom Hooks

Custom hooks have many benefits. They:


Allow code to be abstracted
Hide complex logic
Allow stateful logic to be reused between multiple
components
Print Share

You might also like