'Can the value and setter from useState go into separate contexts?

Given something like the following:

const ctx = createContext([])
const TopLevelComponent = () => {
    const [val, setVal] = useState(0)
    return (
        <ctx.Provider value={[val, setVal]}>
            // actually components go here
        </ctx.Provider>
    )
}

it occurs to me that any child component that uses this ctx gets both the setter and value, but if that child component only sets a value, it doesn't actually need to re-render when the value changes. Given that, I thought it might be reasonable to break it out into 2 contexts - one for the getter, one for the setter, like:

const valueCtx = createContext(0)
const setterCtx = createContext(undefined)

const TopLevelComponent = () => {
    const [val, setVal] = useState(ctx)
    return (
        <valueCtx.Provider value={val}>
            <setterCtx.Provider value={setVal}>
                // actually components go here
            </setterCtx.Provider>
        </valueCtx.Provider>
    )
}

So my question is, fundamentally, is my understanding of how react rerenders accurate? Is there any issue with doing this?

Secondly, if this is a reasonable approach, how does react know to rerender components that rely on valueCtx after a call to the setter contained in setterCtx?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source