score:3

Accepted answer

1. setting parent state for dynamic context

firstly, in order to have a dynamic context which can be passed to the consumers, i'll use the parent's state. this ensures that i've a single source of truth going forth. for example, my parent app will look like this:

const app = () => {
  const [name, setname] = usestate("john");
  const value = { name, setname };

  return (
   ...
  );
};

the name is stored in the state. we will pass both name and the setter function setname via context later.

2. creating a context

next, i created a name context like this:

// set the defaults
const namecontext = react.createcontext({
  name: "john",
  setname: () => {}
});

here i'm setting the defaults for name ('john') and a setname function which will be sent by the context provider to the consumer(s). these are only defaults and i'll provide their values when using the provider component in the parent app.

3. creating a context consumer

in order to have the name switcher set the name and also showing, it should have the access to the name setter function via context. it can look something like this:

const nameswitcher = () => {
const { name, setname } = usecontext(namecontext);
 return (
    <label>your name:</label><br />
    <input type='text' onchange={e => setname(e.target.value)} />
    <p>{name}</p>
  );
};

here i'm just setting the name to input value but you may have your own logic to set name for this.

4. wrapping the consumer in a provider

now i'll render my name switcher component in a namecontext.provider and pass in the values which have to be sent via context to any level deeper. here's how my parent app look like:

const app = () => {
   const [name, setname] = usestate("john");
   const value = { name, setname };

   return (
    <name.provider value={value}>
      <nameswitcher />
    </name.provider>
   );
};

score:2

you need to export your usercontext, so it can be imported in the components that need it:

export const usercontext = react.createcontext();

function app() {
  const [name, setname] = usestate('name');

  return (
    <usercontext.provider value={{ name, setname }}>
      <home />
    </usercontext.provider>
  );
}

afterwards you can import it in your app component:

import { usercontext } '../../app'

function home() {
    const user = usecontext(usercontext);

    return (
        <>
            <label>your name:</label>
            <input type='text' onchange={e => user.setname(e.target.value)} />
            <p>{user.name}</p>
        </>
    )
}

Related Query

More Query from same tag