Jack Gentry
Jack Gentry

Reputation: 327

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;

Upvotes: 26

Views: 32107

Answers (2)

Ashish
Ashish

Reputation: 4330

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.

Upvotes: 22

Fernando Souza
Fernando Souza

Reputation: 844

Your example is totally fine and can be used. setCount is just a function. From your example, the state belongs to the parent component. However, its value will come from another component API.

The same would happen if you change the child component in your example for a regular <button onClick={} />.

I know that this example probably doesn't match your real case implementation. I'd only suggest you pay attention to how the child component API is designed in order to make the parent not tightly coupled to the child.

Upvotes: 0

Related Questions