0

I have this code

  const [magicValue, setMagicValue] = useState([]) // assume that the value is now ["1"]
  
  useEffect(() => {
    const socket = socketIOClient(ENDPOINT)
    socket.on("webhook", (data) => {
      console.log(magicValue) // this will always be []
    })
  }, [])

The problem is that I seem to always have the magicValue as [] even if the state ["1"]. I even create a button to log that indeed the state is updated to ["1"], but for some reason, in the useEffect I get []

johnnyshrewd
  • 1,038
  • 2
  • 12
  • 29
  • Does changing your `useEffect` capture to `[magicValue]` fix the problem? I don't think this has anything to do with socket.io, although this isn't quite a [mcve]. – ggorlen Jul 26 '20 at 23:22
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – ggorlen Jul 26 '20 at 23:23
  • replacing [] with magicValue work. tnx – johnnyshrewd Jul 26 '20 at 23:26
  • 1
    using magicValue as a dependency for the useEffect will cause the event handler to be recreated each time magicValue changes. If magicValue is changing often you might need to look at a different approach. – Jacob Smit Jul 26 '20 at 23:44
  • Yeah, that's a good point--there's probably not much sense in putting a `socket.on` inside `useEffect` in most cases. – ggorlen Jul 27 '20 at 00:55

0 Answers0