1

I'm working with the React Context API, and I've got the following as an example

import React, { createContext, useState } from 'react';

const FooContext = createContext({
  bar: false,
  toggleBar: () => {}
});

export const FooContextConsumer = FooContext.Consumer;

export const FooContextProvider = ({ children }) => {
  const [bar, setBar] = useState(false);

  const toggleBar = () => setBar(!bar);

  return (
    <FooContext.Provider value={{ bar, toggleBar }}>
      {children}
    </FooContext.Provider>
  )
};

export default FooContext;

Now, there's a lot of exports going on here. I know that the createContext functions has { Provider, Consumer } destructure properties available. Is there a way I can use that to compact this code? I've got something like this in mind but that isn't valid syntax unfortunately..

import React, { createContext, useState } from 'react';

export default ({ Provider, Consumer }) = createContext({
  bar: false,
  toggleBar: () => {}
});

export const FooContextConsumer = Consumer;

export const FooContextProvider = ({ children }) => {
  const [bar, setBar] = useState(false);

  const toggleBar = () => setBar(!bar);

  return (
    <Provider value={{ bar, toggleBar }}>
      {children}
    </Provider>
  )
};

So, I want to export createContext function as the default, while using the Provider and Consumer properties of that function within the same file. Is this possible?

Of course I can do it with a const and an export default but I was wondering if this is possible as a one-liner.

2 Answers 2

1

You have to name your context in order to further use it in the file:

import React, { createContext, useState } from 'react';

const Context = createContext({
  bar: false,
  toggleBar: () => {}
});

export const FooContextConsumer = Context.Consumer;

export const FooContextProvider = ({ children }) => {
  const [bar, setBar] = useState(false);

  const toggleBar = () => setBar(!bar);

  return (
    <Context.Provider value={{ bar, toggleBar }}>
      {children}
    </Context.Provider>
  )
};

export default Context;

The implementation I'd recommend for consuming the context:

import React, { createContext, useContext, useState } from 'react';

// ...

export const useFooContext = () => useContext(Context);

// ...

Sign up to request clarification or add additional context in comments.

Comments

1

I would stick to your first example. It's clear which Context the Consumer, and Provider belong to.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.