Languages
[Edit]
EN

React - how to pass object between components using useContext

0 points
Created by:
Selina-Miranda
737

In this article, we would like to show you how to pass data between components using useContext hook in React.

In below example we create UserContext context object which will help us to share some data between components. Each context object contains Provider component that let us share some information with its children - in below example it is UserContext.Provider component with user object set as value property. To get access to the shared value in child components, it is necessary to use useContext hook with context object - in below example it is useContext(UserContext) used inside BoldUser and ItalicUser components.

Note: take at account, we are able to get context access even if child component is nested multiple times (BoldUser inside BoldUserWrapper inside App).

Runnable example:

// ONLINE-RUNNER:browser;

//import React from 'react';
//import ReactDOM from 'react-dom';

const UserContext = React.createContext();

const BoldUser = () => {
    const user = React.useContext(UserContext);
    return (<b>{user.name} {user.age}</b>);
};

const ItalicUser = () => {
    const user = React.useContext(UserContext);
    return (<i>{user.name} {user.age}</i>);
};

const BoldUserWrapper = () => {
	return (<BoldUser />);
};

const ItalicUserWrapper = () => {
	return (<ItalicUser />);
};

const App = () => {
  const user = {
     	name: 'John',
    	age: 25
  };
  return (
    <UserContext.Provider value={user}>
      <BoldUserWrapper />
      <br/>
      <ItalicUserWrapper />
    </UserContext.Provider>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

Alternative titles

  1. React - how to pass object between components without props
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - pass object between components using useContext
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join