How To Use React Context In NextJS With Typescript?
Last Updated :
30 Jun, 2024
React introduced Context to simply managing global consistent states in application. In this article we will how to use React Context for consistent states across various components with Next.js, the most popular and widely used React meta framework, and with TypeScript or complete type safety.
Prerequisites:
React Context
React context allows to share same state across entire application. You do not have to pass state and values from parent to child component. It is helpful for global state management like theming, authentication etc.
Why use react context?
Context solves the age old problem of prop drilling. Prop drilling not only reduces performance but also code base becomes more cumbersome and changes made in one component does not reflect on other components.
createContext
It is used to create context that component can provide or read. It is a function that returns a context object.
Props:
- defaultValue: The value you want to show when there is no matching provider. This is static and never changes overtime. Pass null no meaningful value is need.
JavaScript
'use client';
import { createContext } from "react";
const SomeContext = createContext(null);
export default SomeContext;
useContext
It is a hook that lets you subscribe to context. You have to pass context to it.
JavaScript
import { useContext } from "react";
import SomeContext from "./context";
export default function UserDetails() {
const user = useContext(SomeContext);
return (
<>
{user ? (
<div>
<h1>{user.name}</h1>
<p>{user.age}</p>
</div>
) : (
<p>No user found</p>
)}
</>
);
}
Initialise Next.js project
Now lets create a project to see how to use context in Next.js. Use the command to initialise the project
npx create-next-app@latest
Use the below command to start the development server-
npm run dev
Updated package.json:
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.2.4"
}
Here is the final project structure-
Steps to Use with React Context in Next.js
We are going to create a simple project that lets us view and change the of project globally using React Context.
Step 1: In the app directory, create file for context. You have to create context inside of a client component.
Step 2: Now create provider component. In this component, we are using useState to set a default state and changing the state from other components.
Step 3: Create a custom hook which makes using context really easy. Use ThemeProvider to wrap the children in root layout. Do not worry, it not make all components nested inside provider client component. For more details, you can refer to this article.
Step 4: We creating a component to demonstrate how to use and change theme. Step 6: Modify root page file.
JavaScript
//app/theme-context.tsx
'use client';
import { createContext, Dispatch, SetStateAction } from "react";
type TContext = {
theme: "dark" | "light" ;
setTheme: Dispatch<SetStateAction<"dark" | "light">>;
}
const ThemeContext = createContext<TContext | undefined>(undefined);
export default ThemeContext;
JavaScript
//app/theme-provider.tsx
"use client";
import { useState } from "react";
import ThemeContext from "./theme-context";
export default function ThemeProvider({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const [theme, setTheme] = useState<"dark" | "light">("dark");
return (
<>
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
</>
);
}
JavaScript
//app/use-theme.tsx
'use client';
import { useContext } from "react";
import ThemeContext from "./theme-context";
export default function useTheme() {
const consumer = useContext(ThemeContext);
if (!consumer) {
throw new Error("useThemes must be used within a ThemeProvider");
}
return consumer;
}
JavaScript
"use client";
import useTheme from "./use-theme";
export default function ThemeDetails() {
const { theme, setTheme } = useTheme();
return (
<div
className={`w-full h-screen flex justify-center items-center ${
theme === "dark" ? "bg-black text-white" : "bg-white text-black"
}`}
>
<div>
<h1>Current theme</h1>
<p>Theme: {theme}</p>
<button
onClick={() => {
setTheme(theme === "dark" ? "light" : "dark");
}}
>
Toggle theme
</button>
</div>
</div>
);
}
JavaScript
//app/theme-comp.tsx
"use client";
import useTheme from "./use-theme";
export default function ThemeDetails() {
const { theme, setTheme } = useTheme();
return (
<div
className={`w-full h-screen flex justify-center items-center ${
theme === "dark" ? "bg-black text-white" : "bg-white text-black"
}`}
>
<div>
<h1>Current theme</h1>
<p>Theme: {theme}</p>
<button
onClick={() => {
setTheme(theme === "dark" ? "light" : "dark");
}}
>
Toggle theme
</button>
</div>
</div>
);
}
Output:
Similar Reads
How to use Context API with TypeScript and Next.js? The Context API in React provides a way to pass data through the component tree without having to pass props down manually at every level. When working with TypeScript and Next.js, leveraging the Context API allows for a more organized and type-safe approach to managing the global state. In this tut
3 min read
How to Use NextJS in Typescript? TypeScript enhances Next.js applications by adding static type checking and improves developer experience through type safety. Integrating TypeScript into your Next.js project helps catch errors early and improves code maintainability. It offers even greater productivity and robustness to your web d
5 min read
How To Set Up Mongoose With Typescript In NextJS ? Combining Mongoose with TypeScript in a Next.js project is an intelligent approach to develop scalable, type-safe, and maintainable full-stack web applications. Mongoose offers a powerful ODM (Object Data Modeling) layer to interact with MongoDB, and TypeScript provides static typing to detect issue
5 min read
How to redirect in React with Typescript ? Navigating users seamlessly through a React application is a fundamental aspect of creating a smooth and intuitive user experience. In this article, we delve into the world of redirects in React, specifically addressing the use of TypeScript for enhanced type safety and developer productivity.Prereq
2 min read
How to use React Context with React-Redux ? React context with React-Redux is a popular state management library for React applications. Using React context with React-Redux is a powerful way to provide the Redux store to components deep within your component tree without manually passing it down through props. PrerequisitesNode.js and NPMRea
3 min read
How to add TypeScript in Next.js ? In this article, we will learn how to add TypeScript in Next.js.Why should we use TypeScript in our project? The fundamental concept of TypeScript is that it is type-strict, which means that each entity, be it a variable, a function, or an object has a definite data type. It allows minimum bugs in t
5 min read
How to Type a Page Component With Props in Next.js? Next.js is a popular React framework used for building server-side rendered and static web applications. In many situations, we likely import the components wherever necessary in the project and pass the properties or props accordingly to the component. So, in this article, we will create a componen
3 min read
How To Setup Multiple Themes In NextJS With React-Bootstrap? Multiple themes mean providing users with different visual styles or color schemes for an application, enhancing user experience and personalization. In this article, we'll explore how to set up multiple themes in a Next.js application using React-Bootstrap. We'll explore through creating a theme co
3 min read
How to use Bootstrap with NextJS? Next.js is an open-source web development framework based on React and has gained significant popularity due to its amazing features. It is developed by Vercel and Next.js stands out for its robust capabilities, including server-side rendering(SSR) and enhanced search engine optimization (SEO). Next
3 min read
What is the use of React Context in React-Redux? React Context is a feature that React provides us to manage states required in multiple components. Redux is also a state management library and solves the same problem that React Context does but in a different way. In this article, we will see in detail what is react context, why and how to use it
5 min read