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
useEffect
will 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
useRef
returns a mutable ref object whose.current
property 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
.current
property 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
value
prop 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 contextvalue
passed to thatMyContext
provider.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.useReducer
is usually preferable touseState
when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.useReducer
also lets you optimize performance for components that trigger deep updates because you can passdispatch
down 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
useMemo
will only recompute the memoized value when one of the dependencies has changedHelps to avoid expensive calculations on every render
The function passed to
useMemo
runs 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
useMemo
as a performance optimization, not as a semantic guarantee
src/App.js
useDebugValue For Custom Hook Libraries
useDebugValue(value)
useDebugValue
can 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
useLayoutEffect
will be flushed synchronously, before the browser has a chance to paintPrefer the standard
useEffect
when 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