Blogging my journey of learning Full stack devlopment and creating an App to get a hands on knowledge.

Search This Blog

Thursday, 16 February 2023

Useful React Hooks

 Hooks are the function that you hook it to your Functional App. Hooks can manage state's behavior and side effects by isolating them from a component.

Several of Useful Hooks are:

1.UseState

The useState hook is used to create a stateful function component that can be used with JSX.

const [state, updaterFunction] = useState('')

state:Returns current state value
updaterFunction : Updates the State value
useState: Whatever you put in the parenthesis is the default state


2.UseEffect

The useEffect hook has two parameters, the first parameter is the function we want to run while the second parameter is an array of dependencies. If the second parameter is not provided, the hook will run continuously and if the array contains any dependencies in it,the useEffect Hook will only run if one of those dependencies changes.

   useEffect(() =>{//function logic}, [])

With the useEffect hook, you're able to create side effects while maintaining the component's purity. Within this hook, you can send network requests, change the state value.

3.UseContext

The UseContext provides a way to share states or data throughout the React component tree. The main idea of using the context is to allow your components to access global data and re-render when that global data is changed. Context solves the props drilling problem: when you have to pass down props from parents to children. You can hold inside the context: global state, theme, application configuration, authenticated user name, user settings, preferred language.

// context.js
import { createContext } from 'react';
export const Context = createContext('Default Value');

 

 
//App.js
import { Context } from './context';
function App() {
  const value = 'My Context Value';
  return (
    <Context.Provider value={value}>
      <MyComponent />
    </Context.Provider>
  );

 

//MyComponent.js
import { useContext } from 'react';
import { Context } from './context';
function MyComponent() {
  const value = useContext(Context);
  return <span>{value}</span>;

}

The hook returns the value of the context: value = useContext(Context). The hook also makes sure to re-render the component when the context value changes.


4.useMemo

useMemo keeps a function from being executed again if it didn’t receive a set of parameters that were previously used. It returns the results of a function. Use it when you want to prevent some heavy or costly operations from being called on each render.

const memoizedResult = useMemo(() => expensiveComputation(a), [a])

Once memoized, the hook is going to return the memoized value without invoking expensivecomputation(a) unless value a is changed.


5.useCallback

useCallback keep a function from being re-created again, based on a list of dependencies. It returns the function itself. Use it when you want to propagate it to child components, and prevent from a costly function from re-running.

            const cachedFn = useCallback(function, dependencies)

React will give you the same function (not call the function ) again if the dependencies have not changed since the last render. 

6.useRef

useRef returns an object that can persist in an application. The hook has only one property, current, and we can easily pass an argument to it.

1. It allows you to persist values between renders.

const count = useRef(0);

{count.current}

2. Accessing DOM Elements

const inputElement = useRef();
const focusInput = () => {
    inputElement.current.focus();
  };
//render function
 <input type="text" ref={inputElement} />
 <button onClick={focusInput}>Focus Input</button>


3.Tracking State Changes

  const [inputValue, setInputValue] = useState("");
  const previousInputValue = useRef("");
  useEffect(() => {
  previousInputValue.current = inputValue;
  }, [inputValue]);

7.useHistory

It lets you access the history instance used by React Router. Using the history instance you can redirect users to another page. The history instance created by React Router uses a Stack( called “History Stack” ), that stores all the entries the user has visited.

const history = useHistory()
history.push("/dashboard")

8.useNavigate()

useNavigate is part of React Router and has replaced useHistory, although it is similar to useHistory, but with more useful features.

Uses:

Go to the previous or next pages

Redirect user to a specific Url

let navigate = useNavigate()

const handleClick = () => {

      navigate('/aboutpage') }

return(<button onClick={handleClick}> Read More </button>);}

 

0 comments:

Post a Comment

Featured Post

Invoice Portal Project Links

Web App link for Invoice Portal  Invoice Portal App lets an user view and create an Invoice. Features: View the list of Number of Invoices b...

Powered by Blogger.

Popular Posts