Custom Hooks in React

connorholland54

Connor Holland

Posted on June 30, 2021

Custom Hooks in React

During my final project at flatiron school, I found myself writing most if not all my react components as functional components. As we know, with functional components we have to use hooks to be able to access things like state and life cycle methods. When I started to use hooks, I found that using hooks in functional components made everything so much easier. With that I wanted to figure out how to write my own hooks. For example lets create a custom hook that is similar to useState but also synchronizes to local storage.

First lets define our hook, like so...

const useLocalStorage = () => {
}
Enter fullscreen mode Exit fullscreen mode

Something to notice is that to follow react hook conventions we want to put use in front of our hook name. In this case we are creating a hook to save some data to out local storage. The next thing we want to do is use reacts useState hook. We would add it like so.

const useLocalStorage = () => {
  const [name, setName] = useState(localStorage.getItem('name') || '');
}
Enter fullscreen mode Exit fullscreen mode

What we are essentially doing is giving the hook its own state which will return a name saved in local storage if it exists. Next we want to add a way to set the local storage name. Wee would use the useEffect hook that react gives us.

const useLocalStorage = () => {
  const [name, setName] = useState(localStorage.getItem('name') || '');

React.useEffect(() => {
 localStorage.setItem('name', name);
}, [name]);

 return [name, setName]
}
Enter fullscreen mode Exit fullscreen mode

What this is now doing is that when we set the name in the state it will trigger the useEffect and set the name stored in state to the localStorage variable 'name'. With that we now have our hook! We can call it like we do with useState.

const [name, setName] = useLocalStorage()
Enter fullscreen mode Exit fullscreen mode

Ta da! You know created and called your own hook!

💖 💪 🙅 🚩
connorholland54
Connor Holland

Posted on June 30, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Angular Form Array
angular Angular Form Array

November 29, 2024

Week 13: Release 0.4: Planning
undefined Week 13: Release 0.4: Planning

November 29, 2024

Can a Solo Developer Build a SaaS App?
undefined Can a Solo Developer Build a SaaS App?

November 29, 2024