Lifting state up

Consider the above diagrammatic representation of a DOM tree where A, B, and C are components making up a part of the tree.

  • Now we have a state in B which is needed by C. There are 2 ways to make the state available to C: one is to lift up the state to A and send it as a prop to C, two is to use Global state management like redux, mobX or context API.
  • The process of lifting a component’s state to the common ancestor so that other cousin components can use it is known as Lifting State Up.
  • Example of lifting state up.
// src/A.js
function A(){
  const [todo, setTodo] = useState([]);
  return(
    <>
      <B setTodo={setTodo}/>
      <C todos={todo}/>
    </>
  );
}

// src/B.js
function B({setTodo}){
  const handleSubmit = useCallback((e)=>{
    e.preventDefault();
    setTodo(prevTodo => [...prevTodo, e.target.elements.todo.value ]
  }, []);
 return(
    <form onSubmit={handleSubmit}>
      <input type="text" id="todo" />
      <button type="submit">Add Todo</button>
    </form>
 );
}

// src/C.js
function C({todo}){
  return(
    <ul>
      {todos.map((todo)=>(
          <li key={todo}>
            {todo}
          </li>
      )}
    </ul>
  );
}