0

Can We use context values to initiate a state variable inside a function component?

Here I am trying to initiate a component state with values from context. But the state doesnot update when context value changes.


function Parent() {
  return (
    <ContextProvider>
      <Child />
    </ContextProvider>
  );
}

function Child() {
  const mycontext = useContext(Context);
  const [items, setItems] = useState(mycontext.users);
  console.log(mycontext.users, items); //after clicking fetch, => [Object, Object,...], [] both are not equal. why??????

  return (
    <>
      <button onClick={() => mycontext.fetch()}>fetch</button>
      {/* <button onClick={()=>mycontext.clear()} >Clear</button> */}
      {items.map(i => (
        <p key={i.id}>{i.name}</p>
      ))}
    </>
  );
}
/* context.js */
const Context = React.createContext();
function ContextProvider({ children }) {
  const [users, setUsers] = useState([]);

  function fetchUsers() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(response => response.json())
      .then(json => setUsers(json));
  }

  return (
    <Context.Provider
      value={{ users, fetch: fetchUsers, clear: () => setUsers([]) }}
    >
      {children}
    </Context.Provider>
  );
}

The above code can be tested in codesandbox.

I can use context values directly, but I want to maintain state inside the component. If we cannot initiate state value with a context value, what is the best approach If I want to get data from context and also want to maintain state internally?

Jay Surya
  • 540
  • 1
  • 8
  • 18

1 Answers1

1

The argument to useState is only used once.

You do not need to copy context value in state and can directly use it from context.

If however you would like to do it you need to make use of useEffect

const [items, setItems] = useState(mycontext.users);

useEffect(() => {
    setItems(mycontext.users);
}, [mycontext.users]);

updated demo

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • Thanks. This worked. Would this be the same case if I use props instead of context, like `const [items, setItems] = useState(props.users);`? i.e Should I use `useEffect` or will the state update as I was thinking? – Jay Surya Jun 05 '20 at 15:47