DEV Community

JC
JC

Posted on

Part 2. Sharing data between siblings components using Context in React with Hooks

Once we've got a context provider defined and in place it's time to make the data available on any child component. For this we will use a hook called useContext.

"useContext accepts a context object and returns the current context value for that context. The current context value is determined by the value prop of the nearest above the calling component in the tree". What this means is this hook will give us access to the prop passing the context defined by the context function and wrap in the provider. Let's see it in the component.


import React, { useContext } from "react";



function Profile()  {

    const pots = useContext(PostContext)
    const setPots = useContext(PostDispatchContext)



   return (
        <> 
   {posts.map(post => <h2>{post}</h2>)}
       </> 

      );
}

export { Profile }


Enter fullscreen mode Exit fullscreen mode

First we import useContext from the react library. Then we define our props calling the hook and passing the context created for the prop. In this case for posts we created PostContext to query the context state and PostDispatchContext to mutate the context state. This will give us access to the props state set as an empty array at first.

And finally we can return the data we need. It's important to notice that setPosts is a function as de-structured. When using it to update posts it expects an object that we can easily iterate as a list of posts.

Context provides a way to pass data through the component tree from parent to child components, without having to pass props down manually at each level. It's specially useful to pass data deeply and great tool as a global state management.

While React Context is native and simple to set, it isn’t a dedicated state management tool like Redux, however it can be really useful for prop drilling.

Thanks for reading..

Top comments (0)