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.

Top comments (0)