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 = () => {
}
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') || '');
}
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]
}
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()
Ta da! You know created and called your own hook!
Top comments (0)