DEV Community

Cover image for Why you should be using React Context more often
Owen Conti 🇨🇦
Owen Conti 🇨🇦

Posted on • Originally published at owenconti.com

Why you should be using React Context more often

When people think of context in a React JS app, they often think of global state. "I need to manage the theme my app is set to use, I can use context for this." While this isn't wrong, context can be used for so much more than that use case. I like to think of it as "encapsulated state".

Think of context as a component in your tree that can provide props directly to any child below it. Combine that with hooks, and you can write some clean APIs for your components. Let's take a look at a simple example using a Modal component.

Here's a look at a modal that accepts an onClose prop which should be called to close the modal. The modal manages its own transition system, so when closing the modal, the modal's custom closeModal needs to be called. After the transition is complete, the passed-in onClose prop will be called.

// inside your Modal component...

const Modal = ({
    title,
    onClose
}) => {
    const closeModal = useCallback(() => {
        // Fake code, pretend to start the closing transition
        // and call `onClose` when the transition is done
        startCloseTransition(onClose);
    }, [onClose]);

    return (
        <ModalOverlay closeModal={closeModal}>
          <ModalContent>
            <ModalHeader title={title} closeModal={closeModal} />

            <ModalBody>
              {React.cloneElement(children, { closeModal })}
            </ModalBody>
          </ModalContent>
        </ModalOverlay>
    );
};
Enter fullscreen mode Exit fullscreen mode

Here's the corresponding component that uses the Modal component above:

const SomeComponent = () => {
    const [modalOpen, setModalOpen] = useState(false);

    return (
        <div>
            <button type="button" onClick={() => setModalOpen(true)}>Open Modal</button>

            {modalOpen ? (
                <Modal title="Some Modal" onClose={() => setModalOpen(false)}>
                    <SomeComponentModalContent />
                </Modal>
            ) : null}
        </div>
    );
};

const SomeComponentModalContent = ({
    closeModal
}) => {
    // `closeModal` is available here because the `Modal`
    // component passes it via the `cloneElement` call
    return (
        <div>
            <p>The content of the modal goes here</p>
            <button type="button" onClick={() => closeModal()}>Close the modal</button>
        </div>
    );
};
Enter fullscreen mode Exit fullscreen mode

Continue reading this post on my website.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay