How To Use (More) React Hooks

Mike Pottebaum
2 min readOct 12, 2020

--

A while ago, I wrote about using the basic React hooks, useState and useEffect. Since then, I’ve been working completely with functional components in React and have been able to explore the other hooks React offers.

useContext

useContext is similar to useState except its meant for global values that need to be used by many components. If you’re familiar with Redux, it’s similar to the Redux store. As a matter of fact, context is provided to components by wrapping them in a Provider, just like Redux.

To establish context, import createContext from React and execute the function:

import React, { createContext } from 'reactconst SampleContext = createContext()

The value that’s returned contains the Provider:

<SampleContext.Provider value={'sample'}>
{children}
</SampleContext.Provider>

Now, any child of this Provider can access the value in SampleContext using useContext:

const sample = useContext(SampleContext)

This is useful if you have a value that needs to be accessed site-wide, like a user object. In fact, you can combine useContext with useState and useEffect to handle everything to do with getting user info and establishing a user login in one Provider component like this:

const UserContext = createContext()const UserContextProvider = ({ children }) => {
const [user, setUser] = useState(null)
const userId = localStorage.getItem('userId')

useEffect(() => {
if(userId) {
getUser(userId)
.then(resp => resp.json())
.then(userData => storeUser(userData))
}, []}
const storeUser = userData => {
setUser(userData)
localStorage.setItem('userId', userData.id)
}
return (
<UserContext.Provider value={{ user, storeUser }})>
{children}
</UserContext.Provider>
}

Now, all components within this UserContextProvider will have access to the user object and the storeUser function by using the context hook:

const { user, storeUser } = useContext(UserContext)

useRef

I think useRef is my favorite hook because it gives you access to the kinds of things that make JavaScript fun. A ref is a reference to the DOM node represented by the JSX component in your code. This allows you to use vanilla JavaScript methods like .focus() or .click().

It’s a little trickier to set up than some of the other hooks, mainly because the DOM has to load before the ref has value. First, you need to declare the ref:

const buttonRef = useRef(null)

Then, you have to point your JSX component to the ref:

<button ref={buttonRef}>Click Me</button>

After the DOM is loaded, the <button> node can be accessed by your JavaScript through buttonRef.current. The fact that the ref is only available after the DOM has loaded is important because buttonRef will initially be null. As a result, make sure to check that a ref has value before trying to use ref.current.

--

--