Search code examples
reactjsuse-effectuse-statereact-functional-component

React set variable value from a call back from child component


I am learning React and need some help in finding out a problem with this code and understanding what am I not doing incorrectly. Parent component is MyMap and it needs values for Lat from its child component which is Search bar. Call back function name is setLatInfo and it will set the value for the lat variable defined in useState.

The error that I am seeing is Assignments to the 'setLatInfo' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect.

on the function setLatInfo = (latInfo: number)

How can I assign a call back function within an useEffect block?

import SearchBar from "../components/SearchBar";

const MyMap: FunctionComponent = () => {
    const [lat, setLat] = useState();
  let setLatInfo: (latInfo: number) => void;

  useEffect(() => {
    const loadData = () => {
      
      // map?.map
     // (map as any)?.map.addLayer(h3Layer);
    };
  
    setLatInfo = (latInfo: number) => {   // this entire function is showing error 
      setLat(latInfo);
      console.log(lat);
      console.log(latInfo);
    };

  }, []);

  return (
    <div>
      <SearchBar
        parentCallbackLat={setLatInfo}
      />
    </div>
  );
};

Solution

  • Best to check out the usCallback syntax and how it works, as well as some examples so you can understand exactly what's happening with it. A basic example for your use case would be:

    const [lat, setLat] = useState();
    
    const setLatInfo = useCallback(latInfo => {
        console.log(latInfo);
        setLat(latInfo);
    },[setLat]);
    
    useEffect(() => {
        setLatInfo("initial value");
    }, [setLatInfo]);
    
    return <SearchBar parentCallbackLat={setLatInfo} />;
    

    Also, just so you know React state changes are async and you can't print their new values on the next line