Why you can't use styled-components with NextJS
Intro
Recently, I was working on Next.js with styled-components. During the development, I've encountered the errors, as follows.
createContext only works in Client Components. Add the "use client" directive at the top of the file to use it.
At first I tried to find the createContext
in the code, but nothing was shown. Then I find out that styled-compoent
in my file is the problem.
Styled-component uses React.context
Next.js has two kinds of routing: App router and Page router. App router is the newer one so official docs recommends to use it. It use react server components(react 18's new feature) and client server components for rendering. In the server component, you can't use browser API or react hooks. You have to change your component to client component by adding 'use client'
at the top of the file.
To use styled-component in my project, I added StyledSheetManager
from the package. Then I found out that I have to declare components to client components(by use client
) whenever I use styled-components
That's because styled-component itself uses React.Context
internally. You can find the code in the repository (as of May) and the open issue complaining about being forced to use client components.
Solutions
1. Refactor your code
If you have common designed components for the client, then just separate components using styled-components only for the view. It would make you to separate layers for the login and the view. It could be good, the downside is that you might have to define so many components and hard to get advantages of React Server Components.
2. Change CSS styling method
If the project is small or under the development, using other methods instead of styled-components can be good solution. In my case, I wanted to make many components as server components for the better performance. So I've been thinking about using Tailwind CSS or SASS. There is some recommendations on NextJS official docs