Search code examples
reactjsargumentsparameter-passinguse-effect

How to return values from UseEffect Hook


I am getting the latitude and longitude from a Use Effect hook (which I am relatively new to). I want to return the values outside the use effect hook and store them in variables or even state if needed. I can console log the values but do i just add a return statement or pass arguments somehow? What feature do i need to make use of? I plan to pass the lat and long data into other parts of code which is why i am trying to retrieve it from the useEffect hook.

useEffect(() => {
    if ("geolocation" in navigator) {
      console.log("Available");
    } else {
      console.log("Not Available");
    }
    navigator.geolocation.getCurrentPosition(function (position) {
      let lat = position.coords.latitude;
      let long = position.coords.longitude;
      console.log(lat);
      console.log(long);
    });
  }, []);
let newLat = lat?
let newLong = long?

Solution

  • You can save them in a state or a reference hook.

    Here is how I would do it with a reference hook:

    const lat = useRef(null);
    const long = useRef(null);
    
    useEffect(() => {
        if ("geolocation" in navigator) {
          console.log("Available");
        } else {
          console.log("Not Available");
        }
        navigator.geolocation.getCurrentPosition(function (position) {
          lat.current = position.coords.latitude;
          long.current = position.coords.longitude;
          console.log(lat);
          console.log(long);
        });
      }, []);
    

    You can then access the lat and long values using .current on them. Changing them will not trigger a re-render.

    If you want to use states you can do it like this

    const [lat, setLat] = useState(null);
    const [long, setLong] = useState(null);
    
    useEffect(() => {
        if ("geolocation" in navigator) {
          console.log("Available");
        } else {
          console.log("Not Available");
        }
        navigator.geolocation.getCurrentPosition(function (position) {
          setLat(position.coords.latitude);
          setLong(position.coords.longitude);
          console.log(lat);
          console.log(long);
        });
      }, [setLat, setLong]);
    

    And you can use them like any normal state.

    Also make sure that their values are not null when trying to use them.