DEV Community

Cover image for Why you should be using React Context more often

Why you should be using React Context more often

owenconti profile image Owen Conti 🇨🇦 Originally published at ・2 min read

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 = ({
}) => {
    const closeModal = useCallback(() => {
        // Fake code, pretend to start the closing transition
        // and call `onClose` when the transition is done
    }, [onClose]);

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

              {React.cloneElement(children, { closeModal })}
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 (
            <button type="button" onClick={() => setModalOpen(true)}>Open Modal</button>

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

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

Continue reading this post on my website.

Discussion (0)

Editor guide