Search code examples
reactjsfunctioncomponentsrender

In React, how do you apply componentDidMount for this type of component?


I have a React 16 application. I have a component constructed like so ...

const AddressInput = (props) => {

  const classes = useStyles();
  const { disabled, error, location, onClear, placeholder, setLocation, showMap, value } = props;

  useEffect(() => {
    console.log("use effect 1 ...");
    if (value && placesRef?.current) {
      placesRef.current.setVal(value);

      if (zoom === 0) {
        setZoom(16);
      }
    }
  }, [placesRef, value, disabled, zoom]);

  useEffect(() => {
    console.log("use effect 2 ...");
    if (location) {
      if (zoom === 0) {
        setZoom(16);
      }
      if (location.lat !== position[0]) {
        setPosition([location.lat, location.lng]);
      }
    }
  }, [location, zoom, position]);

  useEffect(() => {
    console.log("use effect 3 ...");
    console.log("setting " + inputId + " to :" + placeholder);
    if (document.getElementById(inputId)) {
      document.getElementById(inputId).value = placeholder;
    }
  }, [])
    ...
  console.log("after use effect:");
  console.log(placeholder);

  return (
    <div style={error ? { border: "solid red" } : {}}>

    ...
    </div>
  );
};


export default AddressInput;

I would like to execute some code after the component has rendered. Normally I could use componentDidMount, but I'm not sure how to apply that when the component is constructed like above.


Solution

  • Since you're using a pure functional component you can use the useEffect hook (as of React v16.8) like this:

    import React, { useEffect } from "react";
    
    const AddressInput = (props) => {
    
      const classes = useStyles();
      const { disabled, error, location, onClear, placeholder, setLocation, showMap, value } = props;
    
      useEffect(() => {
         // your code here
      }, []) // empty array acts like `componentDidMount()` in a functional component
      return (
        <div style={error ? { border: "solid red" } : {}}>
    
        ...
        </div>
      );
    };
    
    
    export default AddressInput;
    

    You can read more about useEffect here: https://reactjs.org/docs/hooks-effect.html