Jay Surya
Jay Surya

Reputation: 570

use context value as initial state value - react hooks

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?

Upvotes: 0

Views: 2398

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281686

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

Upvotes: 1

Related Questions