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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read