[Nextjs] UseContext to share data across applications.

useContext is provided by React Hook.
It can be used to pass data from one component to another.
This is used when you want to manage state globally, such as user sessions, or when you want to refer to common data from each component.

目次

What is useContext?

When there is data to be shared between components or when global state management is desired, useContext allows data to be shared between various components.

Usually, data between components is passed from parent component to child component using props.
The useContext makes it easier to handle when passing this to many components.

Implement useContext.

UseContext to implement the states and functions managed by the context.

Create a context called DataContext and define the DataValuesType type and initial data.

The DataProvider can pass DataValuesType values to the DataProvider’s descendant components by taking children as arguments.

A useDataContext is provided so that data can be retrieved and referenced from any component, and data can be updated with setData.

import { DataType, DataValuesType } from '@/types/Data'
import { createContext, useState, useContext } from 'react'

const defaultProvider: DataValuesType = {
  data: [],
  setData: () => []
}

const DataContext = createContext(defaultProvider)

export function useDataContext() {
  return useContext(DataContext)
}

export function DataProvider({ children }: { children: React.ReactNode }) {
  const [data, setData] = useState<DataType[]>([])

  const value = {
    data,
    setData
  }

  return <DataContext.Provider value={value}>{children}</DataContext.Provider>
}

Add Provider to layout.tsx

DataProvider so that it can provide data for its descendant components.

import { DataProvider } from '@/context/DataContext'

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
      <html lang='ja'>
       <body>
         <DataProvider>
          {children}
         </DataProvider>
       </body>
     </html>
  }
}

Get data.

Data from useContext.
The values are referenced from the data retrieved here.

It is also possible to update the data from any component using setData.

const { data, setData } = useDataContext()

Update data

UseContext setData to update data.

Since data contains an array, it is possible to add or update existing data by using setData.

 setData([...data,[<DataType>])

Summary

The ability to share data between components leads to simpler code, increased readability and reduced complexity in state management.

However, having everything in useContext can also lead to bloat, reduce readability and trigger unnecessary rendering.
State management that can be completed in components should be managed in components.

よかったらシェアしてね!
目次