Pass down "dispatch" function from Redux useDispatch hook to children components as a prop

Viewed 915

I need to create a shared component that requires state usage (use dispatch function to manipulate the state from the redux store) from the project that using it, and the projects that use this component use Redux as their state management system. So my question is having the "dispatch" function from the useDispatch Hook in the parent component (the projects that using this shared component) pass down to this shared component as a prop for using it inside this component a correct way of implementing it? Would it cause any side effects?

Here is a simple code snippet to demonstrate the implementaion mentioned above:

The parent component:

import React from 'react'
import { useDispatch} from 'react-redux'
import ChildComponent from "./ChildComponent"

export const ParentComponent = () => {
  const dispatch = useDispatch()
  return <div><ChildComponent dispatch={dispatch}/></div>
}

The child component (The shared component):

import React from 'react'

export const ChildComponent= ({dispatch}) => {
  const eventHandler = () => dispatch(action())

  return ...
}

P/S: The code above is only for demonstration purpose, the shared component and the parent component are actually exist in diffrent project.

Thank you for all of your inputs.

1 Answers

you can pass dispatch function like any other function to different components, it's better that if you can use useDispatch hook and if it's not possible for any reason, just pass dispatch function as a prop is a correct way

Related