I have a function component, and I want to force it to re-render.
How can I do so?
Since there\'s no instance this, I cannot call this.forceU
Update react v16.8 (16 Feb 2019 realease)
Since react 16.8 released with hooks, function components are now have the ability to hold persistent state. With that ability you can now mimic a forceUpdate:
function App() {
const [, updateState] = React.useState();
const forceUpdate = React.useCallback(() => updateState({}), []);
console.log("render");
return (
);
}
const rootElement = document.getElementById("root");
ReactDOM.render( , rootElement);
Note that this approach should be re-considered and in most cases when you need to force an update you probably doing something wrong.
Before react 16.8.0
No you can't, State-Less function components are just normal functions that returns jsx, you don't have any access to the React life cycle methods as you are not extending from the React.Component.
Think of function-component as the render method part of the class components.