본문 바로가기

Frontend/React

Hooks - useContext(Global State)

반응형

The useContext is one of the hooks in React. It manages the status of the application like useState with a twist that it does this on a global scope. So unlike useState where a status should be passed from one component to another, any component can access the context regardless of its position hence making it an excellent fit for global status management.

List of Contents

Setting Up a Project

Creating a React App

 

React

React is the most papular framework followed by Angular and Vue. React, like Angular uses components to build an application. However, React does not come with native features like Angular. Instead, it uses other libraries which makes React compact and sma

jin-co.tistory.com

Adding Data

For test purposes, add a data file with some dummy data

const InventoryData = [
  {
    id: 1,
    name: 'item 1',
    quantity: 1,
  },
  {
    id: 2,
    name: 'item 2',
    quantity: 2,
  },
  {
    id: 3,
    name: 'item 3',
    quantity: 3,
  },
  {
    id: 4,
    name: 'item 4',
    quantity: 4,
  },
]

Setting Up Components

To see how a component can access data without depending on the relationships with another component, I created components with a hierarchy

Context Set Up

Adding Context

Context file has two functions inside, the context itself and a provider

Add a .js file and add the code below

import { createContext } from 'react'

const InventoryContext = createContext()

export const InventoryProvider = ({ children }) => {
  return (
    <InventoryContext.Provider value={{

    }}>
      {children}
    </InventoryContext.Provider>
  )
}

export default InventoryContext

Using the Context Provider

Go to the App.js component and import the provider and wrap the entire component with the provider

Using Context

I mentioned that the useContext is similar to useStatus but it actually allows components to access not store the status. So to make the example more realistic we need a hook just for that too. 

With the useState

▶ Initializing useState

Let's see how we can use the useContext with the useState. Import the useState and initialize it

 

To provide variables and functions and such to the provider we need to add them as a value for the provider as shown below.

import { createContext, useState } from 'react'
import InventoryData from '../data/InventoryData'

const InventoryContext = createContext()

export const InventoryProvider = ({ children }) => {
  const [inventory, setInventory] = useState(InventoryData)
  return (
    <InventoryContext.Provider value={{
      inventory
    }}>
      {children}
    </InventoryContext.Provider>
  )
}

export default InventoryContext

▶ Accessing the Data from a Component

To access the data, go to the component that needs the data and import the useContext and initialize it with the context we created above with whatever value you are interested in using as a key inside curly braces.

▶ Example (Creating a List out of the Data)

Let's see how we can make a list out of the data we just added

With the useReducer

Next, let's see how we can use the useReducer

▶ Initializing useReducer

Create a reducer function file

Go to the context file and add import useReducer, add the data. Then initialize the reducer.

 

Initialized values, state, and dispatch will be passed as the parameters for the value attribute for the context provider.

import { createContext, useReducer } from 'react'
import InventoryData from '../data/InventoryData'
import { InventoryReducer } from './InventoryReducer'

const InventoryContext = createContext()

export const InventoryProvider = ({ children }) => {
  const initialState = {
    inventory: InventoryData
  }

  const [state, dispatch] = useReducer(InventoryReducer, initialState)

  return (
    <InventoryContext.Provider value={{
      ...state
    }}>
      {children}
    </InventoryContext.Provider>
  )
}

export default InventoryContext


※ We can add them separately too


▶ Accessing the Data from a Component

To access the data, go to the component that needs the data and import the useContext and initialize it with the context we created above with whatever value you are interested in using as a key inside curly braces.

 

▶ Example (Creating a List out of the Data)

Let's see how we can make a list out of the data we just added

 

 

The useConext allows us to manage global status easily by allowing us to access data from anywhere


References

Traversy Media - YouTube

 

Traversy Media

Traversy Media features the best online web development and programming tutorials for all of the latest web technologies from the building blocks of HTML, CSS & JavaScript to frontend frameworks like React and Vue to backend technologies like Node.js, Pyth

www.youtube.com

 

728x90
반응형