Is there any syntax that would allow assigning useState
outside of the function component? I have tried this so far but it has not worked:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
function App() {
useEffect(() => setStateData("from useEffect"), []);
return <div className="App">{stateData}</div>;
}
const [stateData, setStateData] = App.useState("default value"); // fails
// const [stateData, setStateData] = App.prototype.useState("default value"); // also fails
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
CodeSandbox:
You can use the useState
's update
function outside of a component by assigning it to a variable. Just be sure to clear it when the component unmounts.
/* Reference to hold the update function */
let updateOutside
function App() {
const [state, update] = useState()
useEffect(() => {
/* Assign update to outside variable */
updateOutside = update
/* Unassign when component unmounts */
return () => updateOutside = null
})
return `App State: ${state}`
}
if (updateOutside) updateOutside(/* will re-render App */)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With