Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize third party libraries while using react hooks?

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();
  }, []);
};
like image 594
dannyyy Avatar asked Aug 04 '19 09:08

dannyyy


3 Answers

A simple way would be to initialize outside of a component:

const helperLibrary = new HelperLibrary();

const App = () => {
  const [data, setData] = useState(null);
};


If you need to initialize it conditionally, just before 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();
  }
};
like image 190
Aprillion Avatar answered Sep 21 '22 22:09

Aprillion


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} />
  );
}
like image 35
tonilaukka Avatar answered Sep 18 '22 22:09

tonilaukka


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();
   }, [])
like image 32
ravi Avatar answered Sep 17 '22 22:09

ravi