Using React Context in NextJs 13

šŸ“– Neural networks for Javascript developers

The Neural Networks for JavaScript developers book is almost ready! Learn the basics of AI with TensorFlowJs examples. Join now the presale and get a 15$ coupon off the launching price!

Let's see how we can use NextJs 13 with the React Context API.

We will make an example that uses the React Context API to set a theme color on the pages of our app. Given that we are using the context API the color value is easily sent from one page to another.

Check out this video to see the app in action:

Adding the React Context store to a NextJs app

First, we will need to create the React Context store. We will place it in app/context/theme.js:

// app/context/theme.js

'use client';

import { createContext, useContext, useState } from "react";

const ThemeContext = createContext({})

export const ThemeContextProvider = ({ children }) => {
    const [color, setColor] = useState('red');

    return (
        <ThemeContext.Provider value={{ color, setColor }}>
            {children}
        </ThemeContext.Provider>
    )
};

export const useThemeContext = () => useContext(ThemeContext);

Note the 'use client' directive that marks the context component as a client one. Wrote more about NextJs 13 client components here.

The theme context stores and manipulates only the color value.

Passing the React Context to the NextJs layouts

The next step is to make available the context built in the previous step. Given that we need access to this context on all the pages the best place would be to use the provider in the main layout page:

import { ThemeContextProvider } from './Context/theme'

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <head />
      <body>
        <ThemeContextProvider>
          {children}
        </ThemeContextProvider>
      </body>
    </html>
  )
}

Note that this works because the `children` property from the layout is later used in the context provider:

// app/context/theme.js
<ThemeContext.Provider value={{ color, setColor }}>
    {children}
</ThemeContext.Provider>

Using the React Context within the NextJs 13 pages

Now that the context provider setup is done, the final step will be to read and update the context values.

Our app only has two pages: the main page at `/` and a second page at `/second`. Both of them will have a very similar code:

'use client'
import { useThemeContext } from './Context/theme'
import Link from 'next/link'

export default function Main() {
  const { color, setColor} = useThemeContext();

  return (<>
    <h1 style={{'color': color}}>Main page </h1>
    <p>Current color: {color}</p>
    <button onClick={()=> setColor('blue')}>Set color to blue</button>
    <p><Link href="second">Goto second page</Link></p>
  </>)
}

Both pages are reading the context value and updating it.

Given that also these pages are using hooks we will need to mark them as client components.

And that's it! A small example of the React Context API used in NextJs 13.

The full code of the example is here.

šŸ“– Neural networks for Javascript developers

The Neural Networks for JavaScript developers book is almost ready! Learn the basics of AI with TensorFlowJs examples. Join now the presale and get a 15$ coupon off the launching price!


6 Replies

Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

Neural Networks for JavaScript developers
Presale - 15$ free coupon

Hi friend! Before you go, just wanted to let you know that in March 2023 I will be launching the TensorFlow.Js by Example course.

This course will include basic concepts of AI and Neural Networks done with TensorFlowJs such as:

  • Working with datasets
  • Visualizing training
  • Deep Neural Networks in JavaScript
  • Reinforcement Learning
  • Convolutional neural networks
  • and much more ...

Also, there will be a lot of examples as:

  • Object detection
  • Natural language processing
  • Face and voice recognition
  • Gaming AI

Join now the waiting list and get a 15$ coupon off the launching price!

X