简体   繁体   中英

React Hook useEffect has a missing dependency "messages"

I am trying to use MERN for the first time but now I am stuck with this code that returns the above mentioned warning and though the compilation works but some activities are missing. I am attaching my part of the code along with this.

import React, { useEffect, useState } from "react";
import "./App.css";
import Chat from "./Chat";
import Sidebar from "./Sidebar";
import Pusher from 'pusher-js';
import axios from './axios'

function App() {
  const [messages, setMessages] = useState([])

  useEffect(() =>{
    axios.get('/messages/sync').then((response) => {
      setMessages(response.data)
    })
  }, [])

  useEffect(() => {
    const pusher = new Pusher('----------------', {
      cluster: '^^^'
    });

    const channel = pusher.subscribe('message');
    channel.bind('inserted',(newMessage) => {
      alert(JSON.stringify(newMessage));
      setMessages([...messages, newMessage])
    });
  }, [])

  console.log(messages)

  return (
    <div className="app">
      <div className="app_body">
        <Sidebar />
        <Chat />
      </div>
    </div>
  );
}

export default App;

This is the console output:

Compiled with warnings.

./src/App.js
  Line 27:6:  React Hook useEffect has a missing dependency: 'messages'. Either include it or remove the dependency array. You can also do a functional update 'setMessages(m => ...)' if you only need 'messages' in the 'setMessages' call  react-hooks/exhaustive-deps

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

I am trying to build this app with a online video tutorial but this is the problem that occurs to me. How to fix this issue?

Because you are using state messages in useEffect . You just using function when call setMessages to update state like this:

setMessages(preMessages => ([...preMessages , newMessage]))

Neither of the current existing answers explain why this is necessary.

The useEffect hook can be run in 3 scenarios:

  • useEffect(fn) is run every time your component renders
  • useEffect(fn, []) is run the first time your component mounts
  • useEffect(fn, [var1, var2]) is run initially, and then any time either var1 or var2 changes.

The reason you are getting the warning is that the linter has detected you are using an outside dependency ( messages ) in your function, however it's not listed as an explicit dependency. As such, if messages were to change, the useEffect would have a stale version and it would likely cause bugs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM