Hello everyone, today we will talk about React Hooks and some easy methods and patterns to follow that will make your react code much cleaner, more readable.
Hooks are a new addition in React 16.8. Without writing a class based component you can use state and some other React features .
Below are some of the most commonaly used React Hooks are :
State Hook :
This example renders a counter. When you click the button, it increments the value:
import React, { useState } from 'react'; const Couter=()=> { const [value, setValue] = useState(0); return ( <div> <p>You Value is {value}</p> <button onClick={() => setCosetValueunt(value + 1)}> Click me </button> </div> ); }
By calling useState inside a functional component, you can create a single piece of state associated with that component.
We are using useState here is a React Hook .We are calling it inside a functional component for adding local state data to it. React will store this state data between re-renders.
useState always returns a pair: the current state value and a function that used to update the value of it. You can access this method from an event handler function or somewhere else. It’s
similar to this.setState() funttion in a class bases componet, but it does not merge the old and new state together.
Effect Hook :
You must be familier data subscriptions, fetching, or manually changing the Documet Object Modal from React components before. These are Side Effect operation because they affect other
components and can not be perfomed during rendering.
import React, { useState, useEffect } from 'react'; const useEffectExample =()=> { const [value, setValue] = useState(0); // Similar to componentDidMount and componentDidUpdate: useEffect(() => { // Update the document title using the browser API document.title = `You clicked ${value} times`; }); return ( <div> <p>You clicked {value} times</p> <button onClick={() => setValue(value + 1)}> Click me </button> </div> ); }
You are telling React to run your “effect” function after flushing changes to the DOM by calling useEffect hooks. Effects always declared inside the component so they have access to its
props and state. React used to run the effects after every other render including the first render.
Rules of Hooks :
React Hooks should be called at the Top Level :
Never try to call React Hooks inside the loops, conditions, and nested functions. Rather, use React Hooks at the top level of your functional component.Using this rule, you ensure that Hooks
are called in the same manner each step a component renders. That is the thing which allows React to correctly use the state of Hooks between multiple useState and useEffect calls.
Always Call Hooks from Functional component :
Never call React Hooks from regular JavaScript functions. Rather, you can:
Call Hooks from React function components.
Call Hooks from custom Hooks .
By Using this simple rule, you make sure that all stateful logic in a react component van be visible from its source code.