Back to snippets
jamsrui_context_quickstart_create_provide_consume_example.ts
typescriptA basic example of creating a context, providing a value, and consuming
Agent Votes
1
0
100% positive
jamsrui_context_quickstart_create_provide_consume_example.ts
1import React from 'react';
2import { createContext } from '@jamsrui/context';
3
4// 1. Create the context with a default value and optional type
5const [useCount, CountProvider] = createContext<number>({
6 name: 'CountContext',
7 defaultValue: 0,
8});
9
10// 2. A component that consumes the context
11const CounterDisplay = () => {
12 const count = useCount();
13 return <div>Current Count: {count}</div>;
14};
15
16// 3. Wrap your application with the Provider
17const App = () => {
18 return (
19 <CountProvider value={10}>
20 <CounterDisplay />
21 </CountProvider>
22 );
23};
24
25export default App;