Skip to content

Commit e34ee0e

Browse files
committed
Allow initial value override
1 parent 7285f7d commit e34ee0e

File tree

3 files changed

+27
-4
lines changed

3 files changed

+27
-4
lines changed

docs/createStateContext.md

+9-1
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,17 @@ const Demo = () => {
4848

4949
## Reference
5050

51-
```js
51+
```jsx
5252
const [useSharedState, SharedStateProvider] = createStateContext(initialValue);
5353

54+
// In wrapper
55+
const Wrapper = ({ children }) => (
56+
// You can override the initial value for each Provider
57+
<SharedStateProvider initialValue={overrideInitialValue}>
58+
{ children }
59+
</SharedStateProvider>
60+
)
61+
5462
// In a component
5563
const Component = () => {
5664
const [sharedState, setSharedState] = useSharedState();

src/createStateContext.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import { createFactory, createContext, useContext, useState } from 'react';
22

3-
const createStateContext = <T>(initialValue: T) => {
3+
const createStateContext = <T>(defaultInitialValue: T) => {
44
const context = createContext<[T, React.Dispatch<React.SetStateAction<T>>] | undefined>(undefined);
55
const providerFactory = createFactory(context.Provider);
66

7-
const StateProvider: React.FC = ({ children }) => {
8-
const state = useState<T>(initialValue);
7+
const StateProvider: React.FC<{ initialValue?: T }> = ({ children, initialValue }) => {
8+
const state = useState<T>(initialValue !== undefined ? initialValue : defaultInitialValue);
99
return providerFactory({ value: state }, children);
1010
};
1111

tests/createStateContext.test.tsx

+15
Original file line numberDiff line numberDiff line change
@@ -114,4 +114,19 @@ describe('when using among multiple components', () => {
114114

115115
expect(renderCount).toBe(1);
116116
});
117+
118+
it('should override initialValue', () => {
119+
const { baseElement } = render(
120+
<>
121+
<SharedTextProvider>
122+
<DisplayComponent />
123+
</SharedTextProvider>
124+
<SharedTextProvider initialValue={'other'}>
125+
<DisplayComponent />
126+
</SharedTextProvider>
127+
</>
128+
);
129+
130+
expect(baseElement.innerHTML).toBe('<div><p>init</p><p>other</p></div>');
131+
});
117132
});

0 commit comments

Comments
 (0)