search

Home  >  Q&A  >  body text

Title rewritten as: Variables are not updated when using useState() hook

I'm working on a social network project using React.

I wanted to replace a component from a class component to a function component and use hooks, and then a global problem occurred:

When I switch to a new user, the page displays the status of the previous user

I used the useState() hook, debugged everything, but for some reason when a new state component is rendered it doesn't update

const ProfileStatus = (props) => {
  const [edditMode, setEdditMode] = useState(false);
  const [status, setValue] = useState(props.status || "Empty");

  const onInputChange = (e) => {
    setValue(e.target.value);
  };
  const activateMode = () => {
    setEdditMode(true);
  };
  const deactivateMode = () => {
    setEdditMode(false);
    props.updateUserStatus(status);
  };

I thought the problem was that the container component was still a class component, but after redoing it, nothing changed.

P粉066224086P粉066224086448 days ago582

reply all(1)I'll reply

  • P粉674876385

    P粉6748763852023-09-11 17:31:34

    One solution is to use the useEffect hook to trigger an update when the property changes. You can use this hook to compare the current property with the previous property and then update the state in the state.

    You can use this as a reference and make adjustments based on your own code.

    const ProfileStatus = (props) => {
      const [edditMode, setEdditMode] = useState(false);
      const [status, setValue] = useState(props.status || "Empty");
    
      useEffect(() => {
        setValue(props.status || "Empty");
      }, [props.status]);
    
      const onInputChange = (e) => {
        setValue(e.target.value);
      };
      const activateMode = () => {
        setEdditMode(true);
      };
      const deactivateMode = () => {
        setEdditMode(false);
        props.updateUserStatus(status);
      };

    reply
    0
  • Cancelreply