Member-only story
How to Trigger a Component to Re-render with Hooks in React?
Sometimes, we may want to trigger a component to re-render in a component created with React hooks.
In this article, we’ll look at ways we can trigger a component to re-render in a React component created with hooks.
Update a Prop or State
A component will re-render if a prop or state value changes.
Therefore, we can just trigger a re-rendering of a component when we update a prop or state value.
To update a state, we call a state setter function.
For instance, we can write:
import React, { useState } from "react";export default function App() {
const [count, setCount] = useState(0); return (
<div className="App">
<button onClick={() => setCount((c) => c + 1)}>increment</button>
<p>{count}</p>
</div>
);
}
to add a button that calls setCount
to update the count
state.
We know the App
component re-rendered since the latest value of count
is displayed below it when we click the increment button.
Likewise, we can update a prop value to trigger a re-render of a component.