How to use constructors in functional components using hooks?
The constructor is really useful as we can easily pre-define some attributes before the render. In the case of class-based components, we can very easily use the constructor.
When it comes to the functional components, we don’t have an easy way to use the constructor. But we can of course write custom hooks to achieve what the constructor does.
Following is an example of a custom hook called useConstructor for functional component:
// useConstructor.js import { useRef } from 'react'; /* * Purpose: A custom hook for constructor inside the functional component * * Version: 1.0 */ const useConstructor = (callBack = () => {}) => { const hasBeenCalled = useRef(false); if (hasBeenCalled.current) return; callBack(); hasBeenCalled.current = true; }; export default useConstructor;
Here is how we should use it from other component:
// App.js import React, { useState } from 'react'; import useConstructor from "./Hooks/useConstructor"; function App() { const [initialValue, setInitialValue] = useState(''); useConstructor(() => { console.log('It comes here once'); setInitialValue('This should set before the render'); }); return ( <div className="App"> <header className="App-header"> <h2>{initialValue}</h2> </header> </div> ); } export default App;