I have a component that is being called, then called again with updated information, but the var topics
is not being updated by react. Can someone explain why the first example does not update on the screen, but the second one does? Does it have something to do with the useState call?
App.js calls DisplayQuestions once during initial render, then the page takes in user input and re-renders.
<DisplayQuestionsByTopic topics={topics} />
.....
topics var is NOT updated on screen:
export function DisplayQuestionsByTopic(props) {
console.log(`DisplayQuestionsByTopic`, props.topics)
const [topics, setTopics] = useState(props.topics) //<<<<<<<<
render(<h1>topics.join(',')</h1>)
}
topics var IS updated on screen:
export function DisplayQuestionsByTopic(props) {
console.log(`DisplayQuestionsByTopic`, props.topics)
render(<h1>props.topics.join(',')</h1>) //<<<<<<<<<<<
}
useState(props.topics)
, rerendering will not update it. You will have to unmount it completely and then remount it again for the newprops.topics
to be assigned. If it overrode the state var on every render, it would defeat the idea behind react state. – codemonkeyprops.topics
over and manage it inside a state in the child component, then no. If your requirements allow you to manage it from the parent and send it down as a static variable into the child on every render, then heck yeah. To answer the question of "best practice", one really needs to see the complete picture. – codemonkey