title: Adding a Layer to OpenLayers map in React
body: <p>I'm trying to add some functionality for adding layers onto an openlayers map which I've done before in vanilla js but am new to react and having an issue updating the map to display layers. I saw a few examples where it was recommended to declare the map using useState such as:</p>
  <pre><code>const [map, setMap] = useState();
  const mapElement = useRef();
  const mapRef = useRef();
  mapRef.current = map;
  
  useEffect(() =&gt; {
      const initialMap = new Map({
        target: mapElement.current,
          layers: [
              new TileLayer({
                  source: new OSM(),
              }),
          ],
          view: new View({
              center: [0, 0],
              zoom: 0,
          }),
      });
      setMap(initialMap);
  }, []);
  </code></pre>
  <p>I'm getting an error that map is undefined in addWMSLayer in the code below where I'm trying to get a test layer to render. I think because of how useState is compiled but not sure how to fix that. If anyone could tell me a way to get my layer added I would appreciate it. Here's what I have currently tried:</p>
  <pre><code>const MapBox = () =&gt; {
  
  const [map, setMap] = useState(null);
  const mapElement = useRef();
  const mapRef = useRef();
  mapRef.current = map;
  
  useEffect(() =&gt; {
      const initialMap = new Map({
        target: mapElement.current,
          layers: [
              new TileLayer({
                  source: new OSM(),
              }),
          ],
          view: new View({
              center: [0, 0],
              zoom: 0,
          }),
      });
      setMap(initialMap);
  }, []);
  
  const addWMSLayer = ((url, layer) =&gt; {
      
      let source = new ImageWMS({
          url: url,
          params: {'LAYERS': layer}
      })
  
      let wmsLayer = new Image({
          title: 'Test',
          zIndex: 1,
          visible: true,
          source: source,
          opacity: 0.6
      });
      
      setMap(map.addLayer(wmsLayer));
      mapElement.current = map;
  })
  
  
  addWMSLayer(&quot;https://nowcoast.noaa.gov/arcgis/services/nowcoas/analysis_meteohydro_sfc_qpe_time/MapServer/WmsServer?&quot;, '9');
  
  
  return (
      &lt;div style={{height:'100vh', width:'100%'}}ref={mapElement}&gt;&lt;/div&gt;
  )
  </code></pre>
  <p>}</p>
  <p>export default MapBox;</p>