Having issues with @react-three/drei in next.js environment

Having trouble using drei materials and other features like MeshWobbleMaterial, MeshDistortMaterial, or ContactShadows? You may encounter errors such as:

react-three-fiber.esm.js:1383 Uncaught TypeError: Cannot read property 'getState' of null at useFrame (react-three-fiber.esm.js:1383) at MeshDistortMaterial.js:72 (in the case of MeshDistortMaterial)

The 'null' it references is a result of 'useContext(context)' within the useFrame module in react-three-fiber. It seems related to my use of next.js, version 10.1.3.

Below is the relevant code snippet:

import { useRef, useState, useMemo } from 'react'
import { Canvas } from 'react-three-fiber'
import { Box, MeshDistortMaterial } from '@react-three/drei'
import * as THREE from 'three'
import MyCamera from '../three/MyCamera'

//MATERIAL USAGE BLOCK
const MyBox = function (props) {
    const mesh = useRef()
  
    const [hovered, setHover] = useState(false)
    const [active, setActive] = useState(false)
  
    return (
      <Box
        args={[1, 1, 1]}
        {...props}
        ref={mesh}
        scale={active ? [6, 6, 6] : [5, 5, 5]}
        onClick={() => setActive(!active)}
        onPointerOver={() => setHover(true)}
        onPointerOut={() => setHover(false)}
        castShadow
      >
      
        <MeshDistortMaterial
          attach="material"
          distort={1} // Strength, 0 disables the effect (default=1)
          speed={10} // Speed (default=1)
        />

      </Box>
    )
}

//CANVAS DECLARATION SECTION
export default function Main() { 

  const dirLight = useMemo(()=>{
  
    const light = new THREE.DirectionalLight('white');
    light.castShadow=true;
    //Set up shadow properties for the light
    light.shadow.mapSize.width = 10240 
    ...
    
  },[])

  return (
    <div className="canvasContainer">
    <Canvas 
      linear = "true"
      frameloop="demand" 
      shadows = "true"
      shadowMap
    >
      
      <MyCamera position={[0, 0, 30]} infLimit={-1000} supLimit ={0} />
      
      <ambientLight intensity={0.2}/>

      <primitive object={dirLight} position={[30, 0, 30]} />
      <primitive object={dirLight.target} position={[0, 0, 0]}  />
      
      <mesh receiveShadow position={[0,0,-2]}>
        <planeBufferGeometry attach="geometry" args={[1000, 1000]} />
        <meshStandardMaterial attach="material" color="gray" />
      </mesh>
      
      <MyBox position={[8,0,0]}/>

    </Canvas>
    </div>
  )
}

Any solutions to this issue?

I've installed next-transpile-modules and have included a next.config.js file as follows:

const withTM = require('next-transpile-modules')(['three', '@react-three/drei'])

module.exports = withTM()

Your assistance is greatly appreciated, troubleshooting with next.js can be quite challenging.

Answer №1

Have you attempted to utilize useMemo within a component nested inside Canvas?

I suspect that you may have instantiated a DirectionalLight outside of the scene context, potentially causing this issue.

Answer №2

Just to clear things up, although I initially had the right approach, it turned out that certain packages were causing the bug. After struggling to find a solution for some time, I decided to remove and reinstall all dependencies. Many of these dependencies had updates available, and once they were installed, the issue was resolved.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Seeking a breakdown of fundamental Typescript/Javascript and RxJs code

Trying to make sense of rxjs has been a challenge for me, especially when looking at these specific lines of code: const dispatcher = fn => (...args) => appState.next(fn(...args)); const actionX = dispatcher(data =>({type: 'X', data})); ...

Reverse row changes in Angular Ag-Grid with the click of a button

Developed using Angular and JavaScript technologies. The AG-Grid consists of editable records with the first column being a checkbox. When changes are made to any selected records, clicking on a particular record's checkbox and then pressing a button ...

Receiving a blank string after calling fs.readFile within the chokidar.watch(path_file).on('change', ...) function

This is my current Node project setup: https://github.com/tlg-265/chokidar-issue https://i.stack.imgur.com/qYKlR.png $ git clone https://github.com/tlg-265/chokidar-issue $ cd chokidar-issue $ npm i $ npm run watch-changes The project monitors changes ...

React: An error has occurred - Properties cannot be read from an undefined value

THIS PROBLEM HAS BEEN RESOLVED. To see the solutions, scroll down or click here I've been working on a React project where I need to fetch JSON data from my server and render it using two functions. However, I'm encountering an issue where the v ...

Unusual actions observed with that particular button

Currently, I am working on creating a pomodoro clock using Codepen. While I acknowledge that my code isn't flawless yet, I have encountered a peculiar behavior with the Start button. When I click on it once, the timer starts as expected. However, if I ...

Fetching JSON data from a Node.js server and displaying it in an Angular 6 application

Here is the code snippet from my app.js: app.get('/post', (req,res) =>{ let data = [{ userId: 10, id: 98, title: 'laboriosam dolor voluptates', body: 'doloremque ex facilis sit sint culpa{ userId: 10' ...

AngularJS Data Binding Issue - Watch cycle fails to trigger

View the JSFiddle example here: https://jsfiddle.net/pmgq00fm/1/ I am trying to achieve real-time updating of my NVD3 chart by utilizing the setInterval() function on line 39, which updates the data bound to the directive. Here is a brief overview of the ...

Using jQuery to select all child elements based on a specified condition

Is there a way to locate all instances of .post-comment-replies that have a nested '.post-comment-reply' within them, rather than being at the first level? Currently, the code provided retrieves not only those .post-comment-replies with nested . ...

Error: Vuex commit fails due to JSON circular structure issue

Using Vue.js along with the vuex store, I make an API call to validate an item, which returns arrays of errors and warnings. Below is my vuex action : export function validateitemReview ({ commit, dispatch, state }, { reviewId, type, itemreviewData }) { ...

Unlocking the Secrets of MUI TextField Styling

I am interested in creating a styled component using the styled() function and 'div'. My goal is to apply styles for the div that mimic Material UI's TextField component, including properties such as border and hover effects. Is it feasible ...

Automatically tapping the Quora "expand" button through code

I am attempting to automate the clicking of the "more" button located at the bottom of a page like using watir. Below is the code I currently have: require 'watir-webdriver' b = Watir::Browser.new b.goto 'quora.com/'+ ARGV[2] + ' ...

Exploring the JSON data in Javascript using Ajax

Completely new to Javascript, I am just trying to grasp the basics of the language. Currently, I have a JSON request set up with the following code: function request(){ $.ajax({ dataType: "jsonp", type: 'GET', url: "getWebsite", ...

Utilizing Firebase in place of .json files for the AngularJS Phonecat application

I am currently exploring firebase and attempting to retrieve data using this service from firebase instead of json files. However, I have encountered some challenges in getting it to function properly. This is inspired by the angularjs phonecat example .f ...

"Unable to retrieve user information: No authenticated user found" error occurs when attempting to execute a GraphQL query without proper authentication in

I'm currently working on implementing a graphql mutation through Amplify docs to allow unauthenticated requests access. It seems like this should be achievable based on the documentation. According to the CLI documentation: You can override the aut ...

Dynamically load scripts in angularJs

Having multiple libraries and dependencies in my angularjs application is posing a challenge as I want to load them all using just one script, given that three apps are utilizing these dependencies. Currently, I have this custom script: var initDependenci ...

When conducting a test, it was found that the JSX element labeled as 'AddIcon' does not possess any construct or call signatures

Here is a code snippet I'm currently working with: const tableIcons: Icons = { Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />), Check: forwardRef((props, ref) => <Check {...props} ref={ref} />) }; const AddIcon ...

Retrieving innerHTML with React Hooks

Currently, I am working on creating a questionnaire that consists of multiple input fields. The user's responses are displayed at the bottom in a paragraph form: function App() { const divRef = useRef(null) const [ food, setFood ] = useState(&apos ...

VueJS added a new object to the array, but the data did not update reactively

Here is my current data layout days: [ { id: 0 name: 'Monday', times: [] }, { id: 1 name: 'Tuesday', times: [] } } I have implemented the following function to append an object to the times array. onT ...

Sending information to a PHP script using Ajax

I am working on a project that involves input fields sending data to a PHP page for processing, and then displaying the results without reloading the page. However, I have encountered an issue where no data seems to be passed through. Below is my current s ...

Character count in textarea does not work properly when the page is first loaded

As English is not my first language, I apologize in advance for any grammar mistakes. I have implemented a JavaScript function to count the characters in a textarea. The code works perfectly - it displays the character limit reducing as you type. However, ...