avi
avi

Reputation: 11

Wrapping a third party component in React and exposing its state

I made a component that I want to wrap a 3rd party webcomponent with internal state and lift that state up to the App, so it knows when it changes state and can rewrite that state when needed. I'm not sure if I'm doing it right.

So far my code goes like this (pseudocode for simplicity):

function MyWrapper({state, setState}) {
  const ref = useRef(null);
  const [api, setApi] = useState(null);
  
  useEffect(() => {
    const api = SomeNonReactComponent(ref);
    setApi(api);
  }, [ref]);

  useEffect(() => {
    api.state = state;
  }, [api, state]);
  
  function onStateChanged() {
    setState({...api.state})
  }
  // (this callback is passed to api)

  ...

  return <div ref={ref} />
}
  1. Is my approach generally sound or is there a better best practice?

  2. It looks like this has an issue when user interacts with the component and changes its internal state:

So api.state gets updated to match itself, and we get a rerender that does nothing. Feels very wrong (even if not a big deal in my very small project). What should I do about that?

(most information I could find is about Class Components, not Functional Components)

Upvotes: 1

Views: 183

Answers (0)

Related Questions