If I have a third party library that I would normally initialize like so:
class App {
constructor(props) {
this.helperLibrary = new HelperLibrary();
this.state = { data: null };
}
}
How would I go about initializing it in a functional component using react hooks?
So updated code would look something like:
const App = () => {
const [data, setData] = useState(null);
// Would I write something like this here??
helperLibrary = new HelperLibrary();
// Or would I use something like useEffect since
// constructor runs when the component is created?
useEffect = (() => {
helperLibrary = new HelperLibrary();
}, []);
};
A simple way would be to initialize outside of a component:
const helperLibrary = new HelperLibrary();
const App = () => {
const [data, setData] = useState(null);
};
App
is going to be rendered first time (and not e.g. in different routes), the closest equivalent of constructor would be something like:
const App = () => {
const helperLibrary = useRef(null);
const [data, setData] = useState(null);
// note: useEffect would run AFTER first render, equivalent of componentDidMount,
// for equivalent of consturctor, we need sync code, e.g.:
if (!helperLibrary.current) {
helperLibrary.current = new HelperLibrary();
}
};
In our case we needed to bind the 3rd party library to a DOM element and pass props to init. I ended up using useRef and useEffect together:
const App = (props) => {
const container = useRef()
const helperLibrary = useRef(null)
const [data, setData] = useState(null);
useEffect = (() => {
if (!helperLibrary.current) { // runs only once
helperLibrary.current = new HelperLibrary({
props,
// this needs to be last so it doesn't get owerwritten
container: container.current
})
} else { // if there is a way to update
helperLibrary.current.update({
props
})
}
}, [props]);
return (
<div ref={container} />
);
}
I think using this make sense as the function will be called only once,when the component is mounted, so initialization of the library should be done in this block.
useEffect(() => {
console.log('mounted the component');
helperLibrary = new HelperLibrary();
}, [])
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