Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js: Possible to assign useState() outside function component?

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: Edit objective-worker-qb20h

like image 326
Sean D Avatar asked Dec 16 '19 17:12

Sean D


1 Answers

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 */)
like image 102
laggingreflex Avatar answered Oct 19 '22 23:10

laggingreflex