question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. ItĀ collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

hooks: useContext with useState not updating

See original GitHub issue

Do you want to request a feature or report a bug?

seems it’s a bug. šŸ˜•

What is the current behavior?

Nested context provider and useContext hooks seems to be conflicting, updates get discarded.

What is the expected behavior?

When connecting to a context, it should update whenever it’s value changes.

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?

  • react: 18.8.0-alpha.1 (also reproduced on 16.7.0-alpha.0)
  • browser: chrome 71
  • os: macOS Sierra

more details

While working on a cleanup of a localStorage ā€œconnectionā€, I tried to mix 2 articles ([1] & [2]) from the official react documentation, I’ve implemented it with hooks, but the value seems not to be passing through.

I’ve put up a streamlined demo on codesandbox [3].

The actual implementation is only a couple of lines more (parsing it from and stringifying it to JSON).

Workarounds that I found:

  • If I create a new function on each render around the setValue function, it actually works.
    • but this goes against the advice on [1] about avoiding creating new values.
  • Migrate it to a class and use componentDidUpdate instead of useEffect.
    • I’m actually using this right now, as it works. Including saving a reference to the function in the state.

Is there anything that shouldn’t work on the code below? the effect gets triggered with the changes, but the value doesn’t get updated on the components that consume via hook. see repro code [3]

const createLocalStorage = key => {
    const initialValue = localStorage.getItem(key)
    const ValueContext = createContext(initialValue)
    const SetterContext = createContext(() => {})

    const useStorage = () => [ValueContext, SetterContext].map(useContext)

    const Provider = ({children}) => {
        const [value, setValue] = useState(initialValue)

        useEffect(
            () => {
                console.log('effect', value)
                localStorage.setItem(key, value)
            },
            [value],
        )

        return (
            <ValueContext.Provider value={value}>
                <SetterContext.Provider value={setValue}>
                    {children}
                </SetterContext.Provider>
            </ValueContext.Provider>
        )
    }

    return [Provider, useStorage]
}

[1]: https://reactjs.org/docs/hooks-faq.html#how-to-avoid-passing-callbacks-down [2]: https://reactjs.org/docs/context.html#updating-context-from-a-nested-component [3]: https://codesandbox.io/s/0yzjr8vnrv


hlcecpq

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:1
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

5reactions
gaearoncommented, Jan 27, 2019

I’ve put up a streamlined demo on codesandbox [3].

It looks to me like your useContext calls are in the same component as a Provider. In that sense they’re reading context above the Provider (the default one).

Provider’s value only influences context for components inside of it.

By the way, if you didn’t try to cheat the Hooks rules with code like [A, B].map(useContext) you might have noticed this sooner šŸ˜‰

1reaction
gaearoncommented, Jan 27, 2019

Aaah you’re right I misread your example. Yeah observedBits is the issue here. Seems like a pitfall, but then we also don’t recommend to ever call useContext dynamically so…

Read more comments on GitHub >

github_iconTop Results From Across the Web

useContext not updating on state change in React
Here's a generic recipe for useContext. Say you have a file context.js: import { createContext, useContext, useState } from 'react'; // No ......
Read more >
useContext Hook in React - Pragim Tech
Lets display the Employee salary value in App Component as well as in Employee Component so that we can visualize the Salary Change...
Read more >
[Solved]-React context not updating-Reactjs - appsloveworld
In this case your AppWrapper where you render the context provider is where you need to track state. import React, {useContext, useState, useCallback,...
Read more >
React.js — Basic Hooks (useState, useEffect, & useContext)
They let you use state and other React features without writing a class…A hook is a special function that lets you ā€œhook intoā€...
Read more >
React - Manage state using context API with useState or ...
Context Api uses two main hooks (createContext and useContext), ... same provider will rerender whether they use the updated state or not.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found