Search code examples
reactjsrenderweb-componentuse-effectuse-state

Child component does not rerender when parent changes prop


The parent component:

const Parent =
...
var render = {};
render.value = false;
...

return (
<div>
  <button onClick= { () => {render.value = ! render.value; console.log(render);} } >Change Prop</button>
</div>
<Child render = { render } />
...
)

The child component:

const Child = ({render}) => {
  
    useEffect(() => {
        console.log('This does not show up when i click parents button');
    }, [render]);

return (<div></div>)

Shouldn't the child re render due to prop change ?


Solution

  • I dont think you are updating render value correctly. try this:

    const Parent = () => {
       const [render, setRender] = useState({})
    
      return (
         <div>
           <button onClick={() => setRender({...render, value: false})} >Change 
             Prop
           </button>
           <Child render={render} />
         </div>
      )
    }
    

    that is setting the state of the parent to a new value, which in turn will pass it as a prop to child and trigger a render in the child component

    remember to use state in React components for values that will change and need passing down as props. only reason to not use state is for constant values that do not change