Reputation: 11
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} />
}
Is my approach generally sound or is there a better best practice?
It looks like this has an issue when user interacts with the component and changes its internal state:
api.state
changesonStateChanged()
setState
is called with new statestate
variable is updated and passed back downstate
prop updatesuseEffect
reacts and updates api.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