Search code examples
react-nativeuse-effect

useState in React Native get data of previous state


I have one state

  const [data, setData] = useState("");

And 2 useEffects that call in parallel when component renders

     useEffect(() => {
       socket.on("message",()=>{
         console.log(data)
       })
     }, [socket])

    useEffect(() => {
       const res = getDataFromServer()
       setData(res.data)
     }, [isLoading])

2nd useEffect get data from server and set state but when socket arrive in first useEffect data is on initial state that is empty. How can I get updated state data in first useEffect when socket arrives. If I set data as dependency to first useEffect then socket event is reinitialized and callback is calling multiple times.


Solution

  • You can return a function in useEffect to clean unnecessary handlers / event listeners.

    Effects with Cleanup - React Docs

    In this function you can use the offAny method of socket.io client to remove previous listener.

    useEffect(() => {
      const currentListener = socket.on("message",()=>{
        console.log(data)
      });
    
      return () => {
        socket.offAny(currentListener);
      };
    }, [socket, data]);