rsnext/errors/context-in-server-component.md
Hannes Bornö 50caf8b191
Add helpful error for createContext used in Server Components (#43747)
Format runtime server errors similarly to how build errors [are
formatted](https://github.com/vercel/next.js/blob/canary/packages/next/client/dev/error-overlay/format-webpack-messages.js).
Add helpful message when createContext is used in Server Components.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
2022-12-11 20:46:29 -06:00

30 lines
637 B
Markdown

# createContext in a Server Component
#### Why This Error Occurred
You are using `createContext` in a Server Component but it only works in Client Components.
#### Possible Ways to Fix It
Mark the component using `createContext` as a Client Component by adding `'use client'` at the top of the file.
##### Before
```jsx
import { createContext } from 'react'
const Context = createContext()
```
##### After
```jsx
'use client'
import { createContext } from 'react'
const Context = createContext()
```
### Useful Links
[Server and Client Components](https://beta.nextjs.org/docs/rendering/server-and-client-components#context)