2.1 Branches
A branch is one of Git's most important collaboration tools. It lets you try a feature, fix a bug, or refactor code without disturbing the main line.
A branch is not a copied project
When beginners hear "branch", they often imagine a full copied folder. In Git, a branch is closer to a lightweight pointer to a commit.
git branch
git switch -c feature/searchgit switch -c feature/search creates and switches to a new branch. Future commits then move that branch forward.
A concrete login feature example
Suppose the main branch already has two commits:
A Create project
B Finish homepageNow you want to build a login form. If you edit directly on main, the main line becomes half-finished while you work. A better move is:
git switch main
git switch -c feature/loginAt first, both feature/login and main point to commit B. Then you edit files on feature/login:
# edit app/account/page.tsx
git add app/account/page.tsx
git commit -m "Add login form"This commit moves only feature/login forward to commit C. main still stays at B. That is the core idea of using a branch to isolate work.
Why not do everything on main?
main usually represents the stable line. Keeping new work on a separate branch has three benefits:
- You can return to main and inspect the stable version at any time.
- If the experiment fails, deleting a branch is simpler than cleaning up main.
- In team workflows, code review often happens around branches and Pull Requests.
Common commands
git branch
git switch main
git switch -c feature/login
git switch -git switch - switches back to the previous branch, which is convenient when moving between main and the current feature branch.
git status before switching branches. If the working tree has uncommitted changes, Git may block the switch or carry changes into another branch, which can be confusing.