Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a hook as a prop

Is it acceptable / common to pass in a React Hook as a prop to another Component?
Or are they meant to only belong within the component it is declared in?
The following is just an example to illustrate what I mean by passing it as
a prop from the Parent Component to the Child parent.

import React, { useState } from 'react';

export const Parent = () => {

  const [count, setCount] = useState(0);

  return <div>
    Current count is {count}
    <Child setCount={setCount} /> // passing a hook set call as a prop to child
  </div>
}

const Child = ({setCount}) => {
  setCount(10) // using the hook set call
  return (
    <div>
      Some Child Text
    </div>
  );
};

export default Child;
like image 959
Jack Gentry Avatar asked Mar 25 '21 13:03

Jack Gentry


People also ask

Can we pass hooks as a prop?

setCount is not a hook, it is just another function, So you can pass it as a prop. You can also think of the output of useMemo or useCallback , these can be passed as a prop. useState is a hook, useCallback is a hook, or even for a matter any function, which encapsulates other hooks, these should not be passed as prop.

How do you pass function as props in React hooks?

Define the function in the parent component. Pass it as a prop to the child component, e.g. <Child handleClick={handleClick} /> . Use the function in the child component.

Can we pass a function through props?

Passing Functions to React Components In React, there are several cases where you may want to pass a function (like onClick ) as a prop from a container to a child component — usually in order to let the child notify the parent of some event.

Can I use hook in class component?

You can't use Hooks inside a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component.


1 Answers

setCount is not a hook, it is just another function, So you can pass it as a prop. You can also think of the output of useMemo or useCallback, these can be passed as a prop.

useState is a hook, useCallback is a hook, or even for a matter any function, which encapsulates other hooks, these should not be passed as prop.

Why?

To answer this first think of why would you want to pass the hook as a prop? The benefit of passing the hook as a prop will be that you can conditionally pass another hook / skip the call. But in the case of hooks, It should not be called conditionally. So there is no point. of passing it as a prop, Just import it and use it.

like image 125
Ashish Avatar answered Oct 21 '22 17:10

Ashish