React Hooks – More than just syntax sugar?

React hooks decouples state management from class based react component and allow it to be consumed in functional way. However the overwhelming limitation of “Don’t call Hooks inside loops, conditions, or nested functions” brings a lot of headache to developers.

 

There are 5 most useful hooks.

const [state, setState] = useState(initialState);

useState is a nice and clean way to access react state management.

useEffect(didUpdate);

useEffect combines componentDidMount(), componentDidUpdate() and componentWillUnmount(). It looks nice but in practice if developer identifies similar logic in react life cycle methods, they would abstract them into a separate function anyway. When it comes to clean up registered effects, hooks does not offer more code readability. Further more there is potential performance issue as react cleans up effects on every render.

 

context is a nice feature within react which saves your effort of passing props from parents to deeply nested child. However as complexity grows Redux is often preferred over context

useMemo helps to avoid expensive calculations on every render.

useRef is most used to access an DOM element

const value = useContext(MyContext);
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const refContainer = useRef(initialValue);

Leave a Reply