Access React Context outside of render function
Asked Answered
P

6

133

I am developing a new app using the new React Context API instead of Redux, and before, with Redux, when I needed to get a list of users for example, I simply call in componentDidMount my action, but now with React Context, my actions live inside my Consumer which is inside my render function, which means that every time my render function is called, it will call my action to get my users list and that is not good because I will be doing a lot of unecessary requests.

So, how I can call only one time my action, like in componentDidMount instead of calling in render?

Just to exemplify, look at this code:

Let's suppose that I am wrapping all my Providers in one component, like this:

import React from 'react';

import UserProvider from './UserProvider';
import PostProvider from './PostProvider';

export default class Provider extends React.Component {
  render(){
    return(
      <UserProvider>
        <PostProvider>
          {this.props.children}
        </PostProvider>
      </UserProvider>
    )
  }
}

Then I put this Provider component wrapping all my app, like this:

import React from 'react';
import Provider from './providers/Provider';
import { Router } from './Router';

export default class App extends React.Component {
  render() {
    const Component = Router();
    return(
      <Provider>
        <Component />
      </Provider>
    )
  }
}

Now, at my users view for example, it will be something like this:

import React from 'react';
import UserContext from '../contexts/UserContext';

export default class Users extends React.Component {
  render(){
    return(
      <UserContext.Consumer>
        {({getUsers, users}) => {
          getUsers();
          return(
            <h1>Users</h1>
            <ul>
              {users.map(user) => (
                <li>{user.name}</li>
              )}
            </ul>
          )
        }}
      </UserContext.Consumer>
    )
  }
}

What I want is this:

import React from 'react';
import UserContext from '../contexts/UserContext';

export default class Users extends React.Component {
  componentDidMount(){
    this.props.getUsers();
  }

  render(){
    return(
      <UserContext.Consumer>
        {({users}) => {
          getUsers();
          return(
            <h1>Users</h1>
            <ul>
              {users.map(user) => (
                <li>{user.name}</li>
              )}
            </ul>
          )
        }}
      </UserContext.Consumer>
    )
  }
}

But ofcourse that the example above don't work because the getUsers don't live in my Users view props. What is the right way to do it if this is possible at all?

Plural answered 13/4, 2018 at 5:28 Comment(0)
O
179

EDIT: With the introduction of react-hooks in v16.8.0, you can use context in functional components by making use of useContext hook

const Users = () => {
    const contextValue = useContext(UserContext);
    // rest logic here
}

EDIT: From version 16.6.0 onwards. You can make use of context in lifecycle method using this.context like

class Users extends React.Component {
  componentDidMount() {
    let value = this.context;
    /* perform a side-effect at mount using the value of UserContext */
  }
  componentDidUpdate() {
    let value = this.context;
    /* ... */
  }
  componentWillUnmount() {
    let value = this.context;
    /* ... */
  }
  render() {
    let value = this.context;
    /* render something based on the value of UserContext */
  }
}
Users.contextType = UserContext; // This part is important to access context values

Prior to version 16.6.0, you could do it in the following manner

In order to use Context in your lifecyle method, you would write your component like

class Users extends React.Component {
  componentDidMount(){
    this.props.getUsers();
  }

  render(){
    const { users } = this.props;
    return(

            <h1>Users</h1>
            <ul>
              {users.map(user) => (
                <li>{user.name}</li>
              )}
            </ul>
    )
  }
}
export default props => ( <UserContext.Consumer>
        {({users, getUsers}) => {
           return <Users {...props} users={users} getUsers={getUsers} />
        }}
      </UserContext.Consumer>
)

Generally you would maintain one context in your App and it makes sense to package the above login in an HOC so as to reuse it. You can write it like

import UserContext from 'path/to/UserContext';

const withUserContext = Component => {
  return props => {
    return (
      <UserContext.Consumer>
        {({users, getUsers}) => {
          return <Component {...props} users={users} getUsers={getUsers} />;
        }}
      </UserContext.Consumer>
    );
  };
};

and then you can use it like

export default withUserContext(User);
Opine answered 13/4, 2018 at 6:47 Comment(8)
That is a way to do it! But I am wrapping my components with other stuff, so the code will get more and more complicated doing this way. So, using the with-context library and it's decorators make the code much more simple. But thank's for the answer!Monnet
It doesnt work for me, I use the with-context githubAshmead
Shubham Khatri is correct in his answer, there is just a small typo preventing this from running. The curly braces are preventing the implicit return. Just replace them with parentheses.Aftershaft
The context API documentation says that “[You can reference [this.context] in any of the lifecycle methods](reactjs.org/docs/context.html#classcontexttype)”, but you are implying that's not true? Your code seems to go to some effort to inject the context again into props, instead of where the API says it should be.Ensor
Can you explain how to use the this.context with multiple contexts inside the same component? Let's suppose I have a component that needs to access UserContext and PostContext, how to handle that? What I can see is to create a context mixing both, but that's the only or better solution for this?Monnet
@GustavoMendonça You can only subscribe to a single context using this.context API implementation. If you need to read more than one you need to follow the render prop patternOpine
I see, thanks for the answer! Hope they provide some way to use multiple contexts using just the this.contextMonnet
you can also declare it within the Class as a static, ie: static contextType = UserContext;Papaw
P
4

Ok, I found a way to do this with a limitation. With the with-context library I managed to insert all my consumer data into my component props.

But, to insert more than one consumer into the same component is complicated to do, you have to create mixed consumers with this library, which makes not elegant the code and non productive.

The link to this library: https://github.com/SunHuawei/with-context

EDIT: Actually you don't need to use the multi context api that with-context provide, in fact, you can use the simple api and make a decorator for each of your context and if you want to use more than one consumer in you component, just declare above your class as much decorators as you want!

Plural answered 13/4, 2018 at 6:44 Comment(0)
R
4

You can definitely use the context outside of react component, same way it is implemented here using 'PassAccessTokenProvider':

Context:

import { useState, createContext } from 'react'

const AccessTokenContext = createContext()
const PassAccessTokenProvider = {}

const AccessTokenProvider = ({ children }) => {
  const [accessToken, setAccessToken] = useState()

  PassAccessTokenProvider.accessToken = accessToken
  PassAccessTokenProvider.setAccessToken = setAccessToken

  return (
    <AccessTokenContext.Provider value={{ accessToken, setAccessToken }}>
      {children}
    </AccessTokenContext.Provider>
  )
}

export { AccessTokenContext, AccessTokenProvider, PassAccessTokenProvider }

App.js:

import { AccessTokenProvider } from './context'

<AccessTokenProvider>
  <div className='App'>
  </div>
</AccessTokenProvider>

Use Outside of React Component:

import { PassAccessTokenProvider } from '../context'

// SetValue
PassAccessTokenProvider.setAccessToken('value')
// GetValue
PassAccessTokenProvider.accessToken
Rundlet answered 25/8, 2023 at 23:37 Comment(0)
P
0

For my part it was enough to add .bind(this) to the event. This is how my Component looks like.

// Stores File
class RootStore {
   //...States, etc
}
const myRootContext = React.createContext(new RootStore())
export default myRootContext;


// In Component
class MyComp extends Component {
  static contextType = myRootContext;

  doSomething() {
   console.log()
  }

  render() {
    return <button onClick={this.doSomething.bind(this)}></button>
  }
}
Peursem answered 15/7, 2019 at 14:36 Comment(1)
this code looks a lot simpler, but it doesn't actually access values or interact with the RootStore instance at all. can you show an example split across two files and reactive UI updates?Biosphere
L
0

The following is working for me. This is a HOC that uses useContext and useReducer hooks. There's also a way to interact with sockets in this example.

I'm creating 2 contexts (one for dispatch and one for state). You would first need to wrap some outer component with the SampleProvider HOC. Then by using one or more of the utility functions, you can gain access to the state and/or the dispatch. The withSampleContext is nice because it passes both the dispatch and state. There are also other functions like useSampleState and useSampleDispatch that can be used within a functional component.

This approach allows you to code your React components as you always have without needing to inject any Context specific syntax.

import React, { useEffect, useReducer } from 'react';
import { Client } from '@stomp/stompjs';
import * as SockJS from 'sockjs-client';

const initialState = {
  myList: [],
  myObject: {}
};

export const SampleStateContext = React.createContext(initialState);
export const SampleDispatchContext = React.createContext(null);

const ACTION_TYPE = {
  SET_MY_LIST: 'SET_MY_LIST',
  SET_MY_OBJECT: 'SET_MY_OBJECT'
};

const sampleReducer = (state, action) => {
  switch (action.type) {
    case ACTION_TYPE.SET_MY_LIST:
      return {
        ...state,
        myList: action.myList
      };
    case ACTION_TYPE.SET_MY_OBJECT:
      return {
        ...state,
        myObject: action.myObject
      };
    default: {
      throw new Error(`Unhandled action type: ${action.type}`);
    }
  }
};

/**
 * Provider wrapper that also initializes reducer and socket communication
 * @param children
 * @constructor
 */
export const SampleProvider = ({ children }: any) => {
  const [state, dispatch] = useReducer(sampleReducer, initialState);
  useEffect(() => initializeSocket(dispatch), [initializeSocket]);

  return (
    <SampleStateContext.Provider value={state}>
      <SampleDispatchContext.Provider value={dispatch}>{children}</SampleDispatchContext.Provider>
    </SampleStateContext.Provider>
  );
};

/**
 * HOC function used to wrap component with both state and dispatch contexts
 * @param Component
 */
export const withSampleContext = Component => {
  return props => {
    return (
      <SampleDispatchContext.Consumer>
        {dispatch => (
          <SampleStateContext.Consumer>
            {contexts => <Component {...props} {...contexts} dispatch={dispatch} />}
          </SampleStateContext.Consumer>
        )}
      </SampleDispatchContext.Consumer>
    );
  };
};

/**
 * Use this within a react functional component if you want state
 */
export const useSampleState = () => {
  const context = React.useContext(SampleStateContext);
  if (context === undefined) {
    throw new Error('useSampleState must be used within a SampleProvider');
  }
  return context;
};

/**
 * Use this within a react functional component if you want the dispatch
 */
export const useSampleDispatch = () => {
  const context = React.useContext(SampleDispatchContext);
  if (context === undefined) {
    throw new Error('useSampleDispatch must be used within a SampleProvider');
  }
  return context;
};

/**
 * Sample function that can be imported to set state via dispatch
 * @param dispatch
 * @param obj
 */
export const setMyObject = async (dispatch, obj) => {
  dispatch({ type: ACTION_TYPE.SET_MY_OBJECT, myObject: obj });
};

/**
 * Initialize socket and any subscribers
 * @param dispatch
 */
const initializeSocket = dispatch => {
  const client = new Client({
    brokerURL: 'ws://path-to-socket:port',
    debug: function (str) {
      console.log(str);
    },
    reconnectDelay: 5000,
    heartbeatIncoming: 4000,
    heartbeatOutgoing: 4000
  });

  // Fallback code for http(s)
  if (typeof WebSocket !== 'function') {
    client.webSocketFactory = function () {
      return new SockJS('https://path-to-socket:port');
    };
  }

  const onMessage = msg => {
    dispatch({ type: ACTION_TYPE.SET_MY_LIST, myList: JSON.parse(msg.body) });
  };

  client.onConnect = function (frame) {
    client.subscribe('/topic/someTopic', onMessage);
  };

  client.onStompError = function (frame) {
    console.log('Broker reported error: ' + frame.headers['message']);
    console.log('Additional details: ' + frame.body);
  };
  client.activate();
};
Loughlin answered 18/12, 2020 at 16:36 Comment(0)
D
-21

You have to pass context in higher parent component to get access as a props in child.

Darton answered 19/6, 2018 at 10:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.