Friday, May 8, 2020

Hooks in React 16.8

Hooks were introduces in React 16.8, hooks let us create function components in React with state and other React features. Usually for a React component to have state it should be created as a class component.

React 16.8 introduces the following basic hooks

useState: This hook returns a status property and a function to update the state. The function can be used in the component to update the state properties value.

const [stateProp, setStateFunction] = useState(initialStateObject);

useEffect: This hook allows us to perform side effects like DOM update, times logging etc. in a functional component. It is not recommended to do these in the Main body (Render) of the Functional component, hence useEffect helps us achieve this in a Functional component.
The useEffect hook accecpts a function which can be used to perform side effects.
 
 useEffect(() => {
    // Perform side effects here
    document.title = `You clicked ${count} times`;
  });

useContext: This hook accepts a context object and returns the current context value for that context. A component calling useContext will always re-render when the context value changes.

useContext(MyContext)

Apart from these basic hooks, React 16.8 also introduces the following Additional hooks.

useReducer: Similar to useState, but this hook allows us to trigger an action to change a state prop in the reducer (redux)
useCallback
useMemo
useRef
useImperativeHandle
useLayoutEffect
useDebugValue

Search Flipkart Products:
Flipkart.com

No comments: