Home > OS >  Where should I update my state based on my passed in props?
Where should I update my state based on my passed in props?

Time:09-16

const myComponent({prop1, prop2,...}) => {

    const [state, setState] = useState(....);

    

}

If I want to immediately update my local state based on the props, where should I do this?
Is there a special event or I can do it right after the useState line in my code?

CodePudding user response:

You should use the variable prop as a dependency to useEffect hook:

import { useEffect } from "react";

const myComponent({prop1, prop2,...}) => {

    const [state, setState] = useState(....);
    useEffect(() => {
       // some logic to update local state
       setState(...)
    },[prop1])
    

}
  • Related