Home > OS >  functional component doesn't re-render on props change
functional component doesn't re-render on props change

Time:05-25

In the code below, whenever I get new props from the parent, the new props are logged correctly on the console, but the rendered HTML is never updated after the initial render:

export default function(props) {
  const [state, setState] = useState(props)
  
  // initially, props.something is defined
  // every time props changes (from the parent) props.something is redefined as expected and logged here
  console.log(props.something)
  
  // initially, props.something is rendered correctly
  // every time props.something changes (from the parent) the HTML never updates
  return (
    {state.something && <div>{state.something}</div>}
  )
} 

I already tried using useEffect() even though I don't see the point, but it it didn't fix anything.

CodePudding user response:

State will not update just because props change, this is why you need useEffect.

export default function(props) {
  const [state, setState] = useState(props)

  useEffect(() => {
    setState(props.something)
  }, [props.something])
  
  // initially, props.something is defined
  // every time props changes (from the parent) props.something is redefined as expected and logged here
  console.log(props.something)
  
  // initially, props.something is rendered correctly
  // every time props.something changes (from the parent) the HTML never updates
  return (<div>{state.something}</div>)
} 

adding props.something to the array as the second argument to useEffect tells it to watch for changes to props.something and run the effect when a change was detected.

CodePudding user response:

In your example you copy props to state only once, when initial values set.

It's almost never a good idea to copy props to component state though. You can read about it react docs

  • Related