DEV Community

Cover image for ReactJS Design Pattern ~Provider Pattern with Context API~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

ReactJS Design Pattern ~Provider Pattern with Context API~

・This pattern eludes props drilling by using the context API.

contexts/UserContext.ts

import { createContext } from 'react'

export const UserContext = createContext('Inital user')

Enter fullscreen mode Exit fullscreen mode
components/Dashboard.tsx
import React, { useContext } from 'react'
import { UserContext } from '@contexts/UserContext'

export const Dashboard = () => {
  const userValue = useContext(UserContext)
  return <h1>{userValue}</h1>
}
Enter fullscreen mode Exit fullscreen mode
App.tsx
import React from 'react'
import { UserContext } from '@contexts/UserContext'
import { Dashboard } from '@components/Dashboard'

const App = () => {
  return (
    <div>
      <UserContext.Provider value="React user">
        <Dashboard />
      </UserContext.Provider>
    </div>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

・These snippets show that you can access the centralized state value, in this case, React user, from any component.

Top comments (0)