I have a react functional component that shows list of tags and posts + few static text/decorations. I store the currently selected tag in a state using useState
hook. Posts are fetched by using apollo's useQuery
hook with tag
variable. User should able to select a tag and it will replace the current tag
state - thus the useQuery(POSTS_QUERY)
will re-run with new tag
variable.
const onTagSelectChange = (window: Window,
router: NextRouter,
name: string,
checked: boolean,
tagSetter: React.Dispatch<React.SetStateAction<string>>) => {
if (checked) {
setTagQueryInUrl(window, router, name)
tagSetter(name)
} else {
setTagQueryInUrl(window, router, null)
tagSetter(null)
}
}
const NewsList: NextPage = () => {
const router = useRouter()
const query = router.query as Query
// store tag in state
// initialize tag from `tag` query
const [tag, setTag] = useState(query.tag)
const { data: postsData, loading: postsLoading, error: postsError } = useQuery(
POSTS_QUERY,
{
variables: {
tag: tag
}
}
)
const { data: tagsData, loading: tagsLoading, error: tagsError } = useQuery(TAGS_QUERY)
// show error page if either posts or tags query returned error
if (postsError || tagsError) {
return <Error statusCode={500} />
}
return (
<div>
<h1>Here we have list of news, and I should not re-render everytim :(</h1>
<Tags
loading={tagsLoading}
data={tagsData}
isChecked={(name) => name === tag}
onChange={(name, checked) => onTagSelectChange(window, router, name, checked, setTag)}
/>
<Posts loading={postsLoading} data={postsData} />
</div>
)
}
My question is, why is my h1
block keeps re-rendering even though I don't pass anything to it? Or do I completely misunderstand how react works?
` element is actually being changed. It's possible that the re-rendering you're seeing is because the siblings of the `
– Wex Jan 17 '20 at 16:33` element are being modified, thus their shared parent gets a reflow. You can also test this by moving `
` outside of the `` so that it is no longer a sibling.
` element so that doesn't apply to my case.
– fullmoon6661 Jan 17 '20 at 17:25` isn't being modified. It looks like the `` is the one that's being modified, there is an `
– fullmoon6661 Jan 17 '20 at 17:40