Task 2 ReactHooks
Task 2 ReactHooks
Why Hooks?
• To avoid the difficulties while writing classes – eliminating this keyword, eliminating the
need to bind event handlers adn also classes dont minify well
• Reusing stateful logic is harder by using HoC and render props. It makes code harder to
follow.
• To keep related code together. Usualy in class components its difficult.
Example:
Data fetching code: componentDidMount and componentDidUpdate
EventListeners: componentDidMount and componentWillUnmount
Rules:
Always call hooks at top level (never inside loops).
Call hooks only inside React functions and not inside standard javascript functions.
Some commonly used hooks are useState, useEffect, useRef, useContext, useReducer, useMemo
and useCallback.
We can alos write custom hooks.
useMemo vs useCallback:
• useMemo memoizes the returned value from the function
• useCallback memoizes the actual function itself.