You are currently viewing React basic hooks

React basic hooks

React Hooks: 

Hooks add additional features in the functional component. Hooks can be called inside a functional component and they cannot be conditional. There are lots of hooks in react such as

1. useState(initial state): It will track the state of the application. For example, something occurs after a button click.

Syntax: const [current state, state updater function] = useState(initial state)

1st we need to initialize the state by putting any number, boolean, object, array, or any combination of these. Then we can use the current state variable anywhere inside the function. When we need to update the state,  we need to pass the updated value inside the updater function.

Here initial state is red, updater function is setColor. When we click the button updated state color will be blue.

2. useEffect:

The useEffect Hook allows us to perform side effects or actions in the function components. It does not use components lifecycle methods that are available in class components. It can be used in many ways such as 

  • Fetching data form API
  • Updating DOM directly 
  • set up a couter or subscription

Syntax: useEffect(function, [dependency]);

Here we can fetch data, or set up our side effect task inside the function. And inside the dependency array, we can set up the dependency on which the useEffect re-render the DOM. 

3. useContext: 

useContext is a way to manage state globally all over the components.It can be used together with the useState Hook to share state between deeply nested components more easily than with useState alone.

 When we need the data of multiple layers above then data needs to pass through every component in between but every component doesn’t need them, this process of passing data from one component to another component is called prop drilling.

Context API is the best way to pass data from the parents component to 4-5 layers down component.

Context API is an alternative to prop drilling. It creates a global variable and the data can be accessed by all the components.

4. Custom hooks: 

When we need to re-use any function or some part code multiple time we can create a custom hooks that hold our function. To make a custom hook we need to make the function name staring with ‘use’ such as ‘useCart’

Leave a Reply