React Hooks Cheat Sheet
Tags: react, webdev, javascript, beginners
Published: 2024-01-05 14:41:19

# Hooks Rundown

React Hooks allow users to pass and access data within functional components in React.  They allow users to access built-in React features such as state, context, and more.  If you haven't yet encountered Hooks, read more about them [here.](https://react.dev/reference/react/hooks)


# The Cheat Sheet

The point of this post isn't to teach you hooks; It's to give you an easy guide to refer to without digging through the docs because you forgot some simple syntax.  I'll provide a more in-depth explanation of each hook below if you ever need a refresher.


![Cheat Sheet of React Hooks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4dy2b543ig2i48ru8oue.jpg)
 
## `import { useState, useEffect, useContext, useRef } from 'react'`

## useState : Access and modify internal state objects

`const [name, setName] = useState("default_user")`
 
- Takes one optional parameter that sets the default value of the state object
- Returns a reference to internal state object and a setter function for that state object
- Triggers a rerender of the whole component which is default behavior when state is changed


    
## useEffect : Call a function whenever a component is rendered or a state dependency is changed

`useEffect(callbackFunction, [dependencies])`

- Takes 1 required parameter: *a function* and 1 optional parameter: *an array of dependencies*
    - `[ ]` - no dependencies, only runs on initial component render
    - `[name]` - runs when variable *name* is changed, including initial render
    - `null` - all states are dependencies, runs on initial render and every state change / rerender
- Calls given function whenever dependencies are changed



## useContext : Access internal context props provided by parent

`const user = React.useContext(MyContext)`
    

- Takes one argument: the context object created with `React.createContext()`
- Returns whatever data was passed to the context provider value


1. Create context object

        const UserContext = React.createContext()

2. Create context provider

        function UserProvider({children}){

            const user = {
                name: "puppy_lover_2024",
                avatar: "pexels.com/photo/puppy/"
            }

            return(
                <UserContext.Provider value={user}>
                    {children}
                </UserContext.Provider>
            )
        }

3. Wrap children components in context provider

        function App() {
            return (
                <UserProvider>
                    [screenComponents]
                </UserProvider>
            )
        }

4. Access the context using the useContext in a child component

    `const user = React.useContext(UserContext)`



## useRef - references in internal variable that persists across rerenders but does not trigger them

`const numRenders = useRef(1)`

- Takes one argument: a default value for the variable
- Returns a reference to that variable which has a property `.current` that can be treated like any prop/variable
- Useful for keeping track of previous state values and referencing DOM elements
    ```
    function ReferencedDiv({children}){
        const currentDiv = useRef()
        return(
            <div ref={currentDiv}>
                {children}
            </div>
        )
    }
    ```


## `import { useParams, useRouteError, useOutletContext, useNavigate } from 'react-router-DOM`



## useParams - access data stored in current URL

`const params = useParams()`

- Takes no arguments
- Returns object with a key of whate the router was told to expect and a value of the parameter that exists in the link itself
    - In Router: 
    ```
    {
        path: "/profile/:name", element <ProfilePage/>
    }
    ```
    - In Link: 
    ```
    <Link to={ `/profile/puppy_lover_2024` }>
        View Profile
    </Link>
    ```
    - Returned: 
    ```
    return( useParams() )
    -> { name: "/profile/puppy_lover_2024" }
    ```



## useNavigate - Returns function to programmatically navigate to given route

`const navigate = useNavigate()`

- Takes no arguments
- Returns a function that will navigate to given route param
    ```
    const navigate = useNavigate()

    ...

    navigate("/login")
    ```



## useRouteError - catch any error in the UI and reroute to this component

`const error = useRouteError()`

- Takes no arguments
- Returns the error that caused the reroute to this page / component

## useOutletContext - accesses data stored in the direct parent Outlet's context

`const myData = useOutletContext()`

- Takes no arguments
- Returns the object passed to `context` parameter in parent 
    - In Outlet (parent component): 
    ```
    <Outlet context={ name: "puppy_lover_2024" }>
    ```
    - Returned : 
    ```
    return( useOutletContext() )
    
    -> { name: "/profile/puppy_lover_2024" }
    ```
- Only works if the Outlet is this components direct parent