0

I encountered such a problem that when we have a child component whose state depends on the props of the parent, this does not work quite correctly, I would like to know if it is possible to solve this problem using useLayaoutEffect or what is the best way?

Example

Parent

const Parent = () => {
    const  [filled, setFilled] = useState(false)
  useEffect(()=>{
   ..some logic
   setFilled(true)
  },[])
  return <Input isFilled={isFilled}/>
}

Child

const Input = (props) => {
  const  [filled, setFilled] = useState(props.isFilled || false)
  
  // when isFilled changes child components doens't notified about this changes,
  // so can we solve this with useLayoutEffect?

  useLayoutEffect(()=>{
   setFilled(props.isFilled || false)
 },[props.isFilled])
}

This example may be very simple and silly, but I think the essence of the problem should be clear.

Ksenia
  • 950
  • 6
  • 24
  • `props` is not defined in your parent. Where is that coming from? – Terry Oct 04 '22 at 10:51
  • the problem is not from where props comming, but children do not rerender if the props of the parent change, and if it's ok solve this problem with useLayaoutEffect – Ksenia Oct 04 '22 at 10:55
  • From your code, it looks like you don't have isFilled variable that you are passing down to the child. Looks like you should pass "filled" variable to the child prop – Artem Oct 04 '22 at 10:57
  • There has to be a dupetarget or 20 for this. Converting props to state [is usually an antipattern](https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html), but the documentation [here](https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops) (which links to that previous article) shows how to do it. – T.J. Crowder Oct 04 '22 at 10:58
  • My only suggestion is to make 100% percent sure that prop indeed does change (through browser inspector), and not to try to find complicated solution for a simple mistake – Artem Oct 04 '22 at 11:05

0 Answers0