React Hooks Comprehensive Guide — Best Practices and Code Snippets.

The relation between React and Object.is()

Object.is(25, 25);                // true
Object.is('foo', 'foo'); // true
Object.is('foo', 'bar'); // false
Object.is(null, null); // true
Object.is(undefined, undefined); // true
Object.is(window, window); // true
Object.is([], []); // false
var foo = { a: 1 };
var bar = { a: 1 };
Object.is(foo, foo); // true
Object.is(foo, bar); // false


// Case 2: Signed zero
Object.is(0, -0); // false
Object.is(+0, -0); // false
Object.is(-0, -0); // true
Object.is(0n, -0n); // true

// Case 3: NaN
Object.is(NaN, 0/0); // true
Object.is(NaN, Number.NaN) // true

Let’s talk about React famous Hooks

  • Don’t call Hooks inside loops, conditions, or nested functions.
  • Only call Hooks from React function components.

UseState

import React, { useState, useEffect } from "react";
function EffectsDemo() {
const [isOpen,setIsOpen] = useState(false);
}
import React, { useState, useEffect } from "react";
function EffectsDemo({arg}) {
const [result] = useState(expensiveCalculation(arg));
}

Three ways to memoize expensive calculations

function EffectsDemoMemoHook({arg}) {
const result = useMemo(() => expensiveCalculation(arg), [arg]);
}
function EffectsDemoPassFunctionHook({arg}) {
const [result] = useState(() => expensiveCalculation(arg));
}
function RefHooksComponent(props) {
const ref = useRef(null);
if (ref.current === null) {
ref.current = expensiveCalculation(props.arg);
}
const result = ref.current;
}

UseEffect

  • execute code that only runs once, when the component has been rendered, since the dependency array is empty ([]).
import React, { useState, useEffect } from "react";
function EffectsDemoNoDependency() {
const [title, setTitle] = useState("default title");
useEffect(() => {
console.log("this will occur only once");
},[]);
return (
<div>
<h3>{title}<h3>
</div>
);
}
  • same as above, but will be re-rendered every-time the variables defined in the dependency array will be changed.
import React, { useState, useEffect } from "react";
function EffectsDemoWithDependency({defaultTitle}) {
const [title, setTitle] = useState(defaultTitle);
useEffect(() => {
console.log("this will occur once, and every-time the 'defaultTitle' is changed");
},[defaultTitle]);
return (
<div>
<h3>{title}<h3>
</div>
);
}
  • same as above, but we can add a cleanup function right before the component has removed from the DOM.
import React, { useState, useEffect } from "react";function EffectsDemoWithCleanup({prev}) {
useEffect(() => {
const [count, setCount] = useState(0);
const interval = setInterval(function () {
setCount((prev) => prev + 1);
}, 1000);
// return optional function for cleanup
// in this case acts like componentWillUnmount
return () => clearInterval(interval);
}, []);

Ok, Got it, and how do I fetching data from the backend with useEffect?!

useEffect(() => {
const url = "https://api.adviceslip.com/advice";
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
console.log(json); //{"slip": { "id": 135, "advice": "I.."}}
} catch (error) {
console.log("error", error);
}
};
fetchData();
}, []);

UseLayoutEffect

UseContext

import { useContext, createContext } from 'react';
const UserContext = createContext('Unknown');
function App() {
const userName = "John Smith";
return (
<UserContext.Provider value={userName}>
<Layout>
Main content
</Layout>
</UserContext.Provider>
);
}
function Layout({ children }) {
return (
<div>
<Header />
<main> {children} </main>
</div>
);
}
function Header() {
return (
<header>
<UserInfo />
</header>
);
}
function UserInfo() {
const userName = useContext(UserContext);
return <span>{userName}</span>;
}

useCallback

function getSumFunc() {
return (a, b) => a + b;
}
const sum1 = getSumFunc();
const sum2 = getSumFunc();
sum1(2, 3); // => 5
sum2(3, 2); // => 5
sum1 === sum2; // => false
sum1 === sum1; // => true
Object.is(sum1, sum2) // => false
//why?!
function MyComponent() {
// handleClick is re-created on each render
const handleClick = () => {
console.log('Clicked!');
};
//handleClick is a different function object on every rendering of
MyComponent.
}
import { useCallback } from 'react';
function MyComponent() {
// handleClick is the same function object
const handleClick = useCallback(() => {
console.log('Clicked!');
}, []);
}
import { useCallback } from 'react';
import useSearch from './fetch-items';
export function MyParent({ term }) {
const onItemClick = useCallback(event => {
console.log('You clicked ', event.currentTarget);
}, [term]);
return (
<MyBigList term={term} onItemClick={onItemClick} /> );
}
function MyBigList({ term, onItemClick }) {
const items = useSearch(term);
const map = item => <div onClick={onItemClick}>{item}</div>;
return <div>{items.map(map)}</div>;
}

Wrap Up

✍️ Written by Eran Peled 👨🏻‍💻 🤓 🏋️‍🏸 🚀 🚲 🎸

--

--

--

Hard-working web developer with a flair for creating elegant solutions in the least amount of time. Passionate about software architecture and cloud computing.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Understanding Scope in Javascript

The Best Javascript Meme I’ve Ever Seen, Explained in Detail

Enhancement: New Text Editor

AngularJS security series part 1: Angular $http service

Node.JS Streams — File

Testing React Components

ReactJS the Gamechanger

Is Facebook Built in React?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Eran Peled

Eran Peled

Hard-working web developer with a flair for creating elegant solutions in the least amount of time. Passionate about software architecture and cloud computing.

More from Medium

React: what is the useRef() hook?

Data fetching in React

Learn React by asking questions. React interview questions.

Forms in React

react form