Home > other >  add React state to window object
add React state to window object

Time:01-02

What would be the best way to expose React sate to outside React app, like in window object.

const [expanded, setExpanded] = React.useState(false);
window.expanded = expanded;

Would the above be fine directly in the functional component or maybe there is another way that is preferred and standard?

CodePudding user response:

It depends on what you are trying to achieve. If the goal is to be able to retrieve the value and not listen to its setState event, then this approach would work just fine. Do not that since you are setting the value on the window, this value can be read by other scripts that are not on your website. For example when used with iFrames. Make sure that the data you are setting does not contain sensitive information.

If what you are trying to achieve would also involve knowing when the state changes, then I would suggest you look into using an event driven state update. In this case you would set an event emitter that you can subscribe in order to get a callback when the state changes. Have a look on this for inspiration.

CodePudding user response:

you can use like this:

import React from 'react';

export function App(props) {
  const [count, setCount] = React.useState(0)
  React.useEffect(() => {
    window.f = setCount;


  }, [])
  return (
    <div className='App'>
      {count}
      <button onClick={() => {

        window.f(Date.now())
      }} >

        hello</button>
      <h1>Hello React.</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

// Log to console
console.log('Hello console')
  • Related