Home > Software engineering >  How to pass props from parent to grandchild component in react
How to pass props from parent to grandchild component in react

Time:10-21

I have tried pass value from parent to grandchild component, and it works. While I am thinking if there is another simpler or other way of passing props in shorter path.

What I did is quite cumbersome in codesandbox

CodePudding user response:

Generally it's helpful to consider whether moving state down the hierarchy would be the simplest route. That means lifting the component instantiation to a place closer to the state being used. In your example, that could mean Component_data is used inside Component and passed to its children there, removing one step in the nested data flow. Even better, would be that Child.a accesses Component_data.A directly.

In a real app with cases where accessing the data directly is less feasible, a solution I lean towards is using Context to set data in the parent that retrieves it, and then I can access it however deeply nested the component might be that needs it.

i.e. in App I would create the Context provider, and in ChildA I access it via useContext hook.

Further reading

  1. https://reactjs.org/docs/context.html
  2. https://overreacted.io/before-you-memo/#solution-1-move-state-down (this post is about an alternative to using useMemo but has an illustrative example of why moving state down is a good thing)

CodePudding user response:

There may be a common problem in react world called prop drilling by passing data to children only using props.

I would recommend only 2-level passing, if you need pass data deeper then you probably doing something wrong.

Use one of popular state management library (if your project is big) or React context (which is awesome)

Create a folder called /contexts and put contexts there. The structure of files can be like shown below:

  1. First you need to create a context itself
type ClientContextState = {
  data: User;
  set: (data: User) => void;
  logout: () => void;
};

// empty object as a default value
export const UserContext = createContext<UserContextState>({} as UserContextState);
  1. Then create a Provider wrapper component
export const UserProvider = ({ children }: Props) => {
  const [data, setData] = useState<User>({});
  const sharedState = {
    data,
    set: setData
    logout: () => setData(null)
  }

  return <UserContext.Provider value={sharedState}>{children}</UserContext.Provider>
});
  1. You may also want to have an alias of useContext hook:
export const useUser = () => {
  return useContext(UserContext);
};

After all this whenever you wrap your components or app to <UserProvider>...</UserProvider> you can use our hook to access data and methods form sharedState from any place you want:

export LogoutButton = () => {
  const {data, logout} = useUser();

  return <Button onClick={() => logout()}>Logout from {data.name}</Button>
}

CodePudding user response:

Whenever you want to pass props or data from Grandparent to child component, always use react-redux. This is useful to maintain the state and access the data from anywhere/any component. Another way is to use useContext hooks which you can use to pass the props

Following are the steps to use useContext hooks

A. Creating the context The built-in factory function createContext(default) creates a context instance:

import { createContext } from 'react';
const Context = createContext('Default Value');

The factory function accepts one optional argument: the default value.

B. Providing the context

Context.Provider component available on the context instance is used to provide the context to its child components, no matter how deep they are.

To set the value of context use the value prop available on the

<Context.Provider value={value} />:

function Main() {
  const value = 'My Context Value';
  return (
    <Context.Provider value={value}>
      <MyComponent />
    </Context.Provider>
  );
}

Again, what’s important here is that all the components that’d like later to consume the context have to be wrapped inside the provider component.

If you want to change the context value, simply update the value prop.

C. Consuming the context : Consuming the context can be performed in 2 ways.

The first way, the one I recommend, is to use the useContext(Context) React hook:

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