Skip to content

Commit

Permalink
Router: Use a single RouterContext (#9792)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tobbe authored and jtoar committed Jan 3, 2024
1 parent f917ae9 commit 11b6c87
Showing 1 changed file with 9 additions and 27 deletions.
36 changes: 9 additions & 27 deletions packages/router/src/router-context.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useReducer, createContext, useContext } from 'react'
import React, { createContext, useContext, useMemo } from 'react'

import type { AuthContextInterface } from '@redwoodjs/auth'
import { useNoAuth } from '@redwoodjs/auth'
Expand Down Expand Up @@ -27,46 +27,28 @@ export interface RouterState {

const RouterStateContext = createContext<RouterState | undefined>(undefined)

export interface RouterSetContextProps {
setState: (newState: Partial<RouterState>) => void
}

const RouterSetContext = createContext<
React.Dispatch<Partial<RouterState>> | undefined
>(undefined)

/***
*
* This file splits the context into getter and setter contexts.
* This was originally meant to optimize the number of redraws
* See https://kentcdodds.com/blog/how-to-optimize-your-context-value
*
*/
export interface RouterContextProviderProps
extends Omit<RouterState, 'useAuth'> {
useAuth?: UseAuth
children: React.ReactNode
}

function stateReducer(state: RouterState, newState: Partial<RouterState>) {
return { ...state, ...newState }
}

export const RouterContextProvider: React.FC<RouterContextProviderProps> = ({
useAuth,
paramTypes,
children,
}) => {
const [state, setState] = useReducer(stateReducer, {
useAuth: useAuth || useNoAuth,
paramTypes,
})
const state = useMemo(
() => ({
useAuth: useAuth || useNoAuth,
paramTypes,
}),
[useAuth, paramTypes]
)

return (
<RouterStateContext.Provider value={state}>
<RouterSetContext.Provider value={setState}>
{children}
</RouterSetContext.Provider>
{children}
</RouterStateContext.Provider>
)
}
Expand Down

0 comments on commit 11b6c87

Please sign in to comment.