Quick and Easy React Context Template

This article provides a template for using React Context and Hooks, with a simple list example.

I have laid it out so you can copy and paste, find and replace (I am a poet this morning!).

Context is great when props need to be passed up and down component trees. It simplifies the whole process. Some writers argue that context introduces a complicated abstraction, and that prop drilling can sometimes be a better solution. In very simple cases this can be true, but when scaling an application I find it so much easier to just start with Context.

Everything wrapped up together:

import React, { createContext, useContext, useState } from 'react'

const ListContext = createContext([{}, () => {}])

const ListProvider = props => {
    const [state, setState] = useState({
         itemList: []
    })

    return (
        {props.children}
    )
}

const useListContext = () => {
    const [state, setState] = useContext(ListContext)

    function addItemToList({ someItem }) {
        setState(state => {
            const newList = [...state.itemList, state.value];
            return {
                ...state,
                itemList: newList,
            }
        })
    })

    function resetList() {
        setState(state => ({
            ...state,
            itemList: [],
        }))
    })

    return {
        addItemToState,
        resetList
    }
}

export { ListContext, ListProvider, useListContext }

 

To use Context in a particular area, you need to wrap the components you want to be included in the Context provider. Once that is done, you can just extract the state and run your logic, or include the hooks where needed. Super simple!

Related Posts