state inside useEffect refers the initial state always with React Hooks

后端 未结 1 1156
耶瑟儿~
耶瑟儿~ 2021-02-04 10:31

Every time I emit a message from another component, I can\'t get the full list of messages. Here is the hook and view component:

export function useChat() {
  co         


        
1条回答
  •  囚心锁ツ
    2021-02-04 11:18

    Since you have written your useEffect to execute on initial mount of component, it creates a closure which references the initial value of messages and even if the messages update, it will still refer to the same value on subsequent calls

    You should instead configure the useEffect to run on initial mount and messages change

    export function useChat() {
      const [messages, setMessages] = useState([]);
    
      useEffect(() => {
        const socket = openSocket("http://localhost:3003");
        socket.on("chat message", msg => {
          const newState = update(messages, { $push: [msg] });
          setMessages(newState);
        });
      }, [messages]);
    
      return { messages };
    } 
    

    or else you could use the callback pattern to update state

    export function useChat() {
      const [messages, setMessages] = useState([]);
    
      useEffect(() => {
        const socket = openSocket("http://localhost:3003");
        socket.on("chat message", msg => {
          setMessages(prevMessages => update(prevMessages, { $push: [msg] }););
        });
      }, []);
    
      return { messages };
    }
    

    0 讨论(0)
提交回复
热议问题