# code-snippets/3.9.6/js/utils/hooks.ts

Code Snippets, version 3.9.6. 22 lines.

- Page: https://pluginprobe.com/plugins/code-snippets/3.9.6/code/js/utils/hooks.ts
- Raw: https://pluginprobe.com/plugins/code-snippets/3.9.6/raw/js/utils/hooks.ts
- Modified: 2025-08-29T08:54:36+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/code-snippets/3.9.6/code/js/utils/hooks.ts#L10-L20`.

```typescript
import { createContext, useContext } from 'react'
import type { Context } from 'react'

export const createContextHook = <T>(name: string): [
	Context<T | undefined>,
	() => T
] => {
	const contextValue = createContext<T | undefined>(undefined)

	const useContextHook = (): T => {
		const value = useContext(contextValue)

		if (value === undefined) {
			throw Error(`use${name} can only be used within a ${name} context provider.`)
		}

		return value
	}

	return [contextValue, useContextHook]
}

```
