Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/65883803/pass-down-dispatch-function-from-redux-usedispatch-hook-to-children-components

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...