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.
For instance, we can write:
import React, { useState } from "react";
const Count = ({ count }) => <p>{count}</p>;
export default function App() {
const [count, setCount] = useState(0);
return (
<div className="App">
<button onClick={() => setCount((c) => c + 1)}>increment</button>
<Count count={count} />
</div>
);
}
We have the Count
component that takes the count
prop and renders the count
value.
To make the Count
component re-render, we update the value of the count
prop by updating the value of the count
state in App
.
This part is the same as the previous example.
And we know Count
re-rendered since we see the latest value of count
rendered again.
Forcing a Re-rendering of a React Component
Sometimes, we may want to force a re-rendering of a React component when something external to a component is updated.
To do this, we can create our own hook.
For instance, we can write:
import React, { useCallback, useState } from "react";
let count = 0;
setInterval(() => {
count++;
}, 1000);
const useForceUpdate = () => {
const [, setTick] = useState(0);
const update = useCallback(() => {
setTick((tick) => tick + 1);
}, []);
return update;
};
export default function App() {
const update = useForceUpdate();
return (
<div className="App">
<button onClick={() => update()}>update</button>
<p>{count}</p>
</div>
);
}
We have a setInterval
callback that sets the count
variable’s value.
And we create the useForceUpdate
hook that updates a state with the setTick
function.
setTick
is called in the update
function which we return so we can use it in our component code.
In App
, we call useForceUpdate
to and assigned the returned value to the update
variable.
Then in the button we call update
when we click on it.
Therefore, when we click on it, we see the latest value of count
displayed.
Conclusion
There are several ways to trigger a re-rendering of a React component with React hooks.