Hooks For Everyone
What are React Hooks
Hooks are a new addition in React 16.8. They let you use state and other React features for function based components without writing a class.
A Hook is a special function that lets you “hook into” React features.
When would I use a Hook? If you write a function component and realize you need to add some state to it, previously you had to convert it to a class. Now you can use a Hook inside the existing function component.
useState
can only be used on a function based component, not on a class based component
on a class based component, you just use state as normal
const [value, setValue] = useState(intialState);
/src/App.js
Refactoring a Class Component
Class-based component
src/Toggle.js
Function-based component
src/Toggle.js
useState Part 2
useEffect
The Effect Hook lets you perform side effects in function components
Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects.
There are two common kinds of side effects in React components: those that don’t require cleanup, and those that do
Sometimes, we want to run some additional code after React has updated the DOM
Network requests, manual DOM mutations, and logging are common examples of effects that don’t require a cleanup
some effects do require cleanup, we might want to set up a subscription to some external data source
it is important to clean up so that we don’t introduce a memory leak!
with
useEffectwill run after React has updated the DOM
Creating Custom Hooks
Building your own Hooks lets you extract component logic into reusable functions
src/App/js
src/hooks/useTitleInput.js
Use Refs with useRef
useRefreturns a mutable ref object whose.currentproperty is initialized to the passed argument (initialValue)The returned object will persist for the full lifetime of the component.
handy for keeping any mutable value around similar to how you’d use instance fields in classes
Mutating the
.currentproperty doesn’t cause a re-renderhooks way to interact with DOM nodes via refs
src/App.js
attach a reference to a DOM element
create a new reference
Context with Hooks
Accepts a context object (the value returned from
React.createContext) and returns the current context value for that contextThe current context value is determined by the
valueprop of the nearest<MyContext.Provider>above the calling component in the tree.When the nearest
<MyContext.Provider>above the component updates, this Hook will trigger a rerender with the latest contextvaluepassed to thatMyContextprovider.share state all over you app
create a provider (
export const UserContext = createContext()) and export ituse the created provider (
<UserContext.Provider></UserContext.Provider>)give the provider value (
<UserContext.Provider value={{user:true}}>)
src/App.js
src/hooks/Toggle.js
Advanced State Management with useReducer
const [state, dispatch] = useReducer(reducer, initialArg, init);
An alternative to
useState. Accepts a reducer of type(state, action) => newState, and returns the current state paired with a dispatch method.useReduceris usually preferable touseStatewhen you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.useReduceralso lets you optimize performance for components that trigger deep updates because you can passdispatchdown instead of callbacks
src/App.js
src/Counter.js
useMemo for Expensive Functions
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
Pass a “create” function and an array of dependencies
useMemowill only recompute the memoized value when one of the dependencies has changedHelps to avoid expensive calculations on every render
The function passed to
useMemoruns during renderingDon’t do anything there that you wouldn’t normally do while rendering
side effects belong in
useEffect, notuseMemo
If no array is provided, a new value will be computed on every render
You may rely on
useMemoas a performance optimization, not as a semantic guarantee
src/App.js
useDebugValue For Custom Hook Libraries
useDebugValue(value)
useDebugValuecan be used to display a label for custom hooks in React DevTools
src/hooks/useTitleInput.js
Before useDebugValue


After useDebugValue


useLayoutEffect To Wait For DOM
The signature is identical to
useEffect, but it fires synchronously after all DOM mutationsUse this to read layout from the DOM and synchronously re-render
Updates scheduled inside
useLayoutEffectwill be flushed synchronously, before the browser has a chance to paintPrefer the standard
useEffectwhen possible to avoid blocking visual updates
src/hooks/useBodyLockScroll.js
src/DishForm.js
src/App.js
More Complex Custom Hooks
/src/hooks/useOnClickOutside.js
src/DishForm.js
src/Toggle.js
