Skip to content

Commit

Permalink
chore: use reduceRight to refactor nested providers
Browse files Browse the repository at this point in the history
  • Loading branch information
bobstrange committed Mar 31, 2023
1 parent 77a5fd3 commit 57579e6
Showing 1 changed file with 10 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createContext, ReactNode, useContext, useState } from 'react'
import { createContext, createElement, ReactNode, useContext, useState } from 'react'

const createStateContext = <Value, State>(useValue: (init?: Value) => State) => {
const StateContext = createContext<State | null>(null)
Expand Down Expand Up @@ -58,14 +58,18 @@ const Parent = () => {
}

export const FactoryPatternWithCustomHookExample = () => {
const providers = [
[Count1Provider, { initialValue: 0 }],
[Count2Provider, { initialValue: 0 }],
] as const

return (
<>
<h2>Factory pattern with custom hook example</h2>
<Count1Provider initialValue={0}>
<Count2Provider initialValue={0}>
<Parent />
</Count2Provider>
</Count1Provider>
{providers.reduceRight(
(children, [Component, props]) => createElement(Component, props, children),
<Parent />
)}
</>
)
}

0 comments on commit 57579e6

Please sign in to comment.